
/* COPYRIGHT KILTR */
setInterval("weePipe()", 45000);
setInterval("tinyPipe()", 35000);
var slideshow;
var justPressedEnd = false;
//setTimeout ("expireSession()", 2820000);

function setCaretPosition(pos) {
		if ($('#messageBody').setSelectionRange) {
				$('#messageBody').focus();
        $('#messageBody').setSelectionRange(pos, pos);
    } else if ($('#messageBody').createTextRange) {
        var range = $('#messageBody').createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

(function($,len,createRange,duplicate){
	$.fn.caret=function(options,opt2){
		var start,end,t=this[0],browser=$.browser.msie;
		if(typeof options==="object" && typeof options.start==="number" && typeof options.end==="number") {
			start=options.start;
			end=options.end;
		} else if(typeof options==="number" && typeof opt2==="number"){
			start=options;
			end=opt2;
		} else if(typeof options==="string"){
			if((start=t.value.indexOf(options))>-1) end=start+options[len];
			else start=null;
		} else if(Object.prototype.toString.call(options)==="[object RegExp]"){
			var re=options.exec(t.value);
			if(re != null) {
				start=re.index;
				end=start+re[0][len];
			}
		}
		if(typeof start!="undefined"){
			if(browser){
				var selRange = this[0].createTextRange();
				selRange.collapse(true);
				selRange.moveStart('character', start);
				selRange.moveEnd('character', end-start);
				selRange.select();
			} else {
				this[0].selectionStart=start;
				this[0].selectionEnd=end;
			}
			this[0].focus();
			return this
		} else {
           if(browser){
				var selection=document.selection;
                if (this[0].tagName.toLowerCase() != "textarea") {
                    var val = this.val(),
                    range = selection[createRange]()[duplicate]();
                    range.moveEnd("character", val[len]);
                    var s = (range.text == "" ? val[len]:val.lastIndexOf(range.text));
                    range = selection[createRange]()[duplicate]();
                    range.moveStart("character", -val[len]);
                    var e = range.text[len];
                } else {
                    var range = selection[createRange](),
                    stored_range = range[duplicate]();
                    stored_range.moveToElementText(this[0]);
                    stored_range.setEndPoint('EndToEnd', range);
                    var s = stored_range.text[len] - range.text[len],
                    e = s + range.text[len]
                }
            } else {
				var s=t.selectionStart,
					e=t.selectionEnd;
			}
			var te=t.value.substring(s,e);
			return {start:s,end:e,text:te,replace:function(st){
				return t.value.substring(0,s)+st+t.value.substring(e,t.value[len])
			}}
		}
	}
})(jQuery,"length","createRange","duplicate");


function startSlideShow(){
	slideshow = self.setInterval("slideshowStart()",5000);
  $('#slideshowInterval').html(slideshow);
}

function resetShareBox(){
	$('#postBody').css('width','415px');
	$('#postBody').css('height', '15px');
	$("#postContext").val("");
	$("#chosenContext").html("All contacts");
  $('#StatusUpdate-form').css('width','594px');
  //$('#StatusUpdate-form').css('height','32px');
  $('#contextBar').hide();
  $('#addImage, #addVideo, #addAudio, #addLink').css('background-position', '');
  $('#closeCreatePost').hide();
}

function stopSlideShow(){
	
  var currentInterval = parseInt($('#slideshowInterval').html());
	window.clearInterval(currentInterval);
}

function slideshowStart(){

		var nextSlide = '';
  	var curSlide = parseInt($('#currentImage').html());
    var maxSlide = parseInt($('#imagesFound').html());
    var currentSeed = parseInt($('#currentSeed').html());
     
    if(curSlide==(maxSlide)){
    	nextSlide = $('#img-'+currentSeed+'-1').find('img').attr('src');
      var nextImageSrc = nextSlide.replace(/_thumb\./g, ".");
      var slideNumber = 1;
    }else{
    	nextSlide = $('#img-'+currentSeed+'-'+(curSlide+1)).find('img').attr('src');
    	var nextImageSrc = nextSlide.replace(/_thumb\./g, ".");
    	var slideNumber = (curSlide + 1);
    }
    $('#gallery-viewer-v2-images').fadeOut('1500', function() {
    	$('#gallery-viewer-v2-images').html('<img src=\'' + nextImageSrc + '\' style=\'padding: 12px 0px 0px 0px;max-height:420px;\'>');
    	var t = setTimeout(
      	"$('#gallery-viewer-v2-images').fadeIn('1500')"
        ,1000);
    });
    
    $('#imagesFound').html(maxSlide);
    $('#currentImage').html(slideNumber);
    $('#currentSeed').html(currentSeed);

    var reposition = (($(window).scrollTop()) + 100);
		$('#gallery-viewer-v2').css('margin-top', reposition + 'px');

    $('#currentImage').html(slideNumber);
  	
    
}

/*
* Updates the coordinates of the logged in user.
*/
function StoreUserCoordinates(lat, long) {
    $.post("/Ajax/SetGeography", {
        latitude: lat,
        longitude: long
    }, function (response) {
        if (response == 1) {
            // background success
        }
    });
}

var urlParams = {};

(function () {
    var e,
  d = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); },
  q = window.location.search.substring(1),
  r = /([^&=]+)=?([^&]*)/gi;
  
  while (e = r.exec(q)){
  	urlParams[d(e[1])] = d(e[2]);
	}
  
})();

function setProfileCompleteAmount(percentComplete){    
	for(i=1;i<percentComplete;i++){
  	$('#actualComplete').css('width',i+'%');
  }
  
  $('#percentComplete').html(percentComplete+'% Profile complete');
}

function tinyPipe() {
    if ($('#recently-joined').html() != null) {
            updateWhoHasJoined();
    }
}

function weePipe() {
    updateFloatingNavCount();
    updateNetworkActivityFeed();

}

function updateWhoHasJoined() {
    var newItemDiv = $('#recently-joined .newItems');
    var newItemCount = parseInt(newItemDiv.html());
    var firstReg = $('#recently-joined .carouselItem:first a.newlyRegistered');
    //var lastId = firstReg.attr('id').split('-')[1];
    var createdDate = firstReg.attr('id').split('-')[2];
     $.get("/MyKiltr/GetNewlyJoined", {
        createdDate: createdDate
    }, function (response) {
        var newItems = $('<div>' + response + '</div>');
        var newCount = newItems.find('.carouselItem').length;
        if (newCount > 0) {
            firstReg.parent().before(newItems.html());
            newItemDiv.html(newItemCount + newCount);
        }
    });
}
function in_array (needle, haystack, argStrict) {

    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                
            	return true;
            }
        }
    }
     return false;
}

function pauseNetworkActivityFeed() {
	$('#pauseFeed').val('1');
}

function startNetworkActivityFeed() {
	$('#pauseFeed').val('0');
}

function resetImportTabs() {

    $('#linkedInTabImage').attr('src', '/Images/ported/genericInterface/tabs/linkedInOff.gif');
    $('#gmailTabImage').attr('src', '/Images/ported/genericInterface/tabs/gmailOff.gif');
    $('#macMailTabImage').attr('src', '/Images/ported/genericInterface/tabs/macMailOff.gif');
    $('#outlookExpressTabImage').attr('src', '/Images/ported/genericInterface/tabs/outlookExpressOff.gif');
    $('#outlookTabImage').attr('src', '/Images/ported/genericInterface/tabs/outlookOff.gif');
    $('#hotmailTabImage').attr('src', '/Images/ported/genericInterface/tabs/hotmailOff.gif');
    $('.networkTabOn').removeClass('networkTabOn').addClass('networkTabOff');
}

function strip_tags(str, allowed_tags) {

    // Strips HTML and PHP tags from a string  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/strip_tags    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Tomasz Wesolowski    // *     example 1: strip_tags('<p>Kevin</p> <b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
    var key = '', allowed = false;
    var matches = []; var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }
    str += '';

    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }

        // Save HTML tag
        html = matches[key].toString();
        // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<' + allowed_tag + '>'); } if (i != 0) { i = html.toLowerCase().indexOf('<' + allowed_tag + ' '); }
            if (i != 0) { i = html.toLowerCase().indexOf('</' + allowed_tag); }

            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
    return str;
}

function isIe7() {
    if ($.browser.msie) {
        if (parseInt(jQuery.browser.version) == 7) {
            return true;
        }
        
        if (parseInt(jQuery.browser.version) == 6) {
            return true;
        }
        
        return false;
    }
}

function isIe8orOlder() {
    if ($.browser.msie) {
        if (parseInt(jQuery.browser.version) <= 8) {
            return true;
        }
        return false;
    }
}

function getRelativeDate(s) {
    //HACK: -1 in hours below is just to deal with BST. Need a proper fix soon! (-1 in months is because of stupid javascript!)
    var m = (new Date().getTime() - Date.UTC(s.substring(0, 4), s.substring(4, 6) - 1 /*months*/, s.substring(6, 8), s.substring(8, 10)/*-1*//*hack*/, s.substring(10, 12), s.substring(12, 14))) / 60000;
    if (m < 0.75)
        return "less than a minute";
    else if (m < 1.5)
        return "about a minute";
    else if (m < 45)
        return Math.round(m) + " minutes";
    else if (m < 90)
        return "about an hour";
    else if (m < 60 * 24)
        return "about " + Math.round(m / 60) + " hours";
    else if (m < 60 * 48)
        return "a day";
    else if (m < 60 * 24 * 30)
        return Math.floor(m / 60 / 24) + " days";
    else if (m < 60 * 24 * 60)
        return "about a month";
    else if (m < 60 * 24 * 365)
        return Math.floor(m / 60 / 24 / 30) + " months";
    else if (m < 60 * 24 * 365 * 2)
        return "about a year";
    else
        return Math.floor(m / 60 / 24 / 365) + " years";    
   
}

function updateNetworkActivityFeed(options) {

    $('span.relativeDate, a.relativeDate').each(function (i) {
        $(this).html(getRelativeDate($(this).attr('id').split('-')[1]) + ' ago');
    });

    // are we passed options or setting them?
    if (options == null) {
        options = '';
        var filters = $('.filter');
        if (filters != null && filters.length > 0) {
            for (var i=0; i<filters.length;i++) {
                if ($(filters[i]).is(":checked")) options += filters[i].name + ',';
            }
        }
    }

    var currentUrl = document.location.href;
    var urlParts = currentUrl.split('/');

    //if (urlParts.length == 4 && urlParts[3].toLowerCase() == 'mykiltr') {
    var feedDiv = $('#primaryFeedAlt');
    if (feedDiv.html() != null) {
        var feedStatus = parseInt($('#pauseFeed').val());
        if (feedStatus == 0) {
            //Get Context from More button
            var moreButton = feedDiv.find('.seeMoreItems');
            if (moreButton.length == 0)
                return;

            var context = moreButton.attr('id');
            if (context == null || context.length == 0 || context.split(':').length < 2)
                return;

            //Get first Post and isolate datetime
            var feedItem = feedDiv.find('.feedItem');
            if (feedItem.length == 0 || feedItem.attr('id') == null)
                return;

                var dateString = feedItem.attr('id').split('-')[1];

            if (dateString == '' || isNaN(dateString))
                return;

            //Get HTML back from MyKiltr/GetNetworkActivityFeedLatest (afterDateTime)
            $.post("/Ajax/GetNetworkActivityFeedLatest", {
                afterDateTime: dateString,
                context: context,
                f: options
            },
      function (response) {
          if (response.length > 0) {
              var newElems = $('<div>' + response + '</div>');
              var c = 0;

              //Cycle through new stuff (only the feedItem collection), collecting ID
              newElems.find('.feedItem').each(function (i) {
                  var id = $(this).attr('id');

                  var old = feedDiv.find('[id|="' + id.split('-')[0] + '"]');

                  //If any existing IDs are in new ID list and time is different, remove it
                  if (old != null && old.attr('id') == id) {
                      $(this).parent().remove();
                      c--;
                  }
                  else if (old != null) {
                      old.parent().remove();
                  }
                  c++;
              });
              if (c > 0) {
                  //Insert new items before first post
                  var feedContainer = $('#networkActivityFeedContainer');
                  if (feedContainer.html() != null) {
                      feedContainer.prepend(newElems);
                  }
                  else {
                      feedDiv.find('#clearBothDiv').after(newElems);
                  }

                  //Update NewPosts value by adding net number of new posts.
                  var newCount = $('.newPosts');
                  newCount.html((c + parseInt(newCount.html())));

                  newCount = $('#numberOfNetworkActivityPostsDisplayed');
                  if (newCount != null)
                      newCount.html((c + parseInt(newCount.html())));
              }
              reconnectAddThis();
          }
      });
        }


    }
}

function is_int(input) {

    return typeof (input) == 'number' && parseInt(input) == input;
}

function itemAlreadySelected(tagId, currentListDiv) {

    var x;
    var itemList = currentListDiv.val();
    var itemsArray = itemList.split('|');

    if (jQuery.isArray(itemsArray)) {
        for (x in itemsArray) {
            if (itemsArray[x] == tagId) {
                return true;
            }
        }
    }

    return false;
}

function styleReportWindow() {
    $('#messageWindow').css('background-color', '#CC0033');
    $('.modalWindowHeader').css('background', '#CC0033');
    $('.modalHeader').html('Report');
    $('.messageLabel').css('color', '#000000');
    $('.closeModalDialog').attr('src', '/Images/ported/common/closeReportButtonInverted.gif');
    $('#messageSendButton').attr('src', '/Images/ported/messageCenter/reportButton.gif');
}

function styleMessageWindow() {
    $('#suggestable-user, .recipientClose').css('display', 'inline');
    $('#messageWindow').css('background-color', '#5A95BF');
    $('.modalWindowHeader').css('background', '#5A95BF');
    $('.modalHeader').html('New message');
    $('.messageLabel').css('color', '#5A95BF');
    $('.closeModalDialog').attr('src', '/Images/ported/common/closeButtonInverted.gif');
    $('.closeModalDialog').css('display', 'block');
    $('#messageSendButton').attr('src', '/Images/ported/messageCenter/sendButton.gif');
    
}

function styleReportWindow() {
    $('#suggestable-user, .recipientClose').css('display', 'none');
    $('#messageWindow').css('background-color', '#CC0033');
    $('.modalWindowHeader').css('background', '#CC0033');
    $('.modalHeader').html('Report');
    $('.messageLabel').css('color', '#000000');
    $('.closeModalDialog').attr('src', '/Images/ported/common/closeReportButtonInverted.gif');
    $('#messageSendButton').attr('src', '/Images/ported/messageCenter/reportButton.gif');
}

$.fn.extend({ 
	disableSelection: function() { 
 		this.each(function() { 
    	if (typeof this.onselectstart != 'undefined') {
      	this.onselectstart = function() { return false; };
     	} else if (typeof this.style.MozUserSelect != 'undefined') {
      	this.style.MozUserSelect = 'none';
     	} else {
      	this.onmousedown = function() { return false; };
      }
		}); 
	}
});


function updatedPickedQty() {

    var itemListDiv = $('#selectedIds');
    var currentRecipients = itemListDiv.val();
    recipientsArray = currentRecipients.split('|');
    var counter = 0;
    var currentContext = $('#postContext').val();
		
    for (x in recipientsArray) {
        counter++;
    }
		
    var currentContext = $('#currentChoice').html();
    
    if (currentContext == 'SelectGroups') {
        contextDesc = 'Selected groups';
    } else if (currentContext == 'SelectContacts' || currentContext == 'Contacts') {
        contextDesc = 'Selected contacts';
    } else if (currentContext == 'SelectOrganisations') {
        contextDesc = 'Selected organisations';
    } else if (currentContext == 'SelectEvents') {
        contextDesc = 'Selected events';
    } else {
        contextDesc = 'Selected';
    }

    $('#chosenContext').html(contextDesc + ' (' + (counter - 1) + ')');
}


function updateFloatingNavCount() {

    currentUnreadMessages = parseInt($('#messageQty').html());
    currentUnreadInvites = parseInt($('#inviteQty').html());

    $('#inviteAlert').load('/Ajax/InviteAlert', function () {
        currentUnreadInvitesAfterUpdate = parseInt($('#inviteQty').html());

        if (currentUnreadInvites == -1) {    // session expired
            pauseNetworkActivityFeed();
            window.location = "/Account/LogOff";
        } else if (currentUnreadInvitesAfterUpdate > 0) {
            $('#inviteMaster').attr('src', '/Images/ported/genericInterface/floatingNav/invites_active.gif');
        } else {
            $('#inviteMaster').attr('src', '/Images/ported/genericInterface/floatingNav/invites.png');
        }

        if (currentUnreadInvites != currentUnreadInvitesAfterUpdate) {
            if (currentUnreadInvitesAfterUpdate > 0) {

                $('.rightNavInviteCount').html(currentUnreadInvitesAfterUpdate);

                $("#accordionSmall").accordion("option", "active", 1);
                $.post("/Invite/RenderMiniInviteWidget", {

            }, function (response) {
                $('#miniInviteWidget').html(response);
            });
            
        }
    }
});

$('#messageAlert').load('/Ajax/MessageAlert', function () {
    currentUnreadMessagesAfterUpdate = parseInt($('#messageQty').html());

    if (currentUnreadMessagesAfterUpdate == -1) {    // session expired
        pauseNetworkActivityFeed();
        window.location = "/Account/LogOff";
    } else if (currentUnreadMessagesAfterUpdate > 0) {
        $('#mailMaster').attr('src', '/Images/ported/genericInterface/floatingNav/inbox_active.gif');
    } else {
        $('#mailMaster').attr('src', '/Images/ported/genericInterface/floatingNav/mail.png');
    }

    if (currentUnreadMessages != currentUnreadMessagesAfterUpdate) {
        if (currentUnreadMessagesAfterUpdate > 0) {
            $('.rightNavMessageCount').html(currentUnreadMessagesAfterUpdate);

            $("#accordionSmall").accordion("option", "active", 0);

            $.post("/Message/GetMiniMessageWidgetContent", {
                retrievalType: 'received'
            }, function (response) {
                $('#miniMessages').html(response);
            });
        }
    }
});
}

function spawnModalDialogueWindow(width, height, title, ajaxDestinationUrl, passthroughVar) {
		
    var innerWindowPadding = 31;
    var innerWidth = (width - innerWindowPadding);
    var innerHeight = (height - innerWindowPadding);
		
    $('#emptyModalDialogue').css('margin-top', '45px');
    $('#emptyModalDialogue, #emptyModalWindow').css('width', width);
    $('#emptyModalWindowOverlay').css('width', innerWidth);
    $('#emptyModalDialogue, #emptyModalWindow').css('height', height);
    $('#emptyModalWindowOverlay').css('height', innerHeight);

    $('#emptyModalDialogue').show();
    $('.emptyModalTitle').html(title);
    $("#emptyModalDialogue").draggable({ handle: '.modalHeader' });
    
    //$('#emptyModalWindowBody').load(ajaxDestinationUrl);

    $.post(ajaxDestinationUrl, {
        passedVar: passthroughVar
    }, function (response) {
        $('#emptyModalWindowBody').html(response);
    });
}

function setAutoScroll(moreButton, on) {
    if (on && moreButton.hasClass('noAutoLoad')) {
        moreButton.removeClass('noAutoLoad');
    } else if (!on && !moreButton.hasClass('noAutoLoad')) {
        moreButton.addClass('noAutoLoad');
    }
}

function loadMore(moreButton) {
    if (justPressedEnd) {
        setAutoScroll(moreButton, false);
        justPressedEnd = false;
        return false;
    }
    moreButton.find('.moreLoader').show();
    moreButton.children('.seeMoreLink').hide();
    var context = moreButton.attr('id');
    var currentPageNumber = parseInt(moreButton.find('.pageNumber').html());
    var nextPage = (currentPageNumber + 1);
    moreButton.find('.pageNumber').html(nextPage);
    var options = $('.alphaBiteOn').html();
    if (options == null) {
        options = '';
        var filters = $('.filter');
        if (filters != null && filters.length > 0) {
            for (var i = 0; i < filters.length; i++) {
                if ($(filters[i]).is(":checked")) options += filters[i].name + ',';
            }
        }
    }

    var newItems = moreButton.find('.newPosts').html();

    if (context.match(/^SharedConnections/)) {  // v4
        moreSharedConnections(moreButton, context.split(':')[1], currentPageNumber);
    }
    else if (context.match(/^UserPickerCardList/)) { // enough already going to AJAX controller! (v2)
        postToPaging(moreButton, context, currentPageNumber);
    }
    else if (context.match(/^UpcomingEvents/)) {    // v3
        context = moreButton.siblings('.timeDepiction:last').html();
        getMoreEvents(moreButton, context, currentPageNumber);
    }
    else if (context.match(/^More/)) {  // most recent model for paging (v5)
        moreItems(moreButton, currentPageNumber, context.substring(4).replace(/-/g, '/'));
    }
    else {
        seeMoreItems(moreButton, context, currentPageNumber, newItems, options);    // v1
    }
    return false;
}

function reconnectAddThis() {
    if (window.addthis) {
        window.addthis = null;
    }
    $.getScript('http://s7.addthis.com/js/250/addthis_widget.js#pubid=kiltr');
}

function seeMoreItems(moreButton, context, currentPageNumber, newItems, options) {
    var slowFetch = false;
    var timerId = setTimeout(function () { slowFetch = true; }, 1000);
    $.post("/Ajax/SeeMoreItems", {
        context: context,
        options: options,
        pageNumber: currentPageNumber,
        newItems: newItems
    }, function (response) {
        //clearTimeout(timerId);
        if (slowFetch) {
            setAutoScroll(moreButton, false);
        }
        var responseParts = response.split("\07\07");
        insertNewItems(moreButton, responseParts[1]);
        if (responseParts[0] == 'True') {
            moreButton.hide();
        }
        reconnectAddThis();
    });    
}

function moreItems(moreButton, currentPageNumber, url) {
    $.get(url, {
        page: currentPageNumber
    }, function (response) {
        insertNewItems(moreButton, response);
    });
}

function moreSharedConnections(moreButton, userId, currentPageNumber) {
    var container = moreButton.parents('.container');
    var offset = container.offsetTop;
    $.get("/People/GetSharedConnections", {
        userId: userId,
        page: currentPageNumber
    }, function (response) {
        insertNewItems(moreButton, response);
        $("#mcs10_container").mCustomScrollbar("vertical", 400, "easeOutCirc", 1.05, "auto", "yes", "yes", 10);
        container.scrollTo(offset + 'px', 500);
    });
}

function ShowSharedConnections() { //copied from kiltr-v2 (hack to get diaspora hovercards to work, to be fixed, though probably in kiltr-v2)
    $(this).html("");
    $(this).unbind("click"); //unbind click event handler. No need to worry about rebinding as it's done when hovercard reloaded
    $('.sharedConnectionsContainer').html('<img id=\'gallery-post-loader\' src=\'/Images/ported/ajax-loader-white.gif\' style=\"z-index: 110000; text-align:center;margin: 0 auto;\">');
    $('.sharedConnectionsContainer').show();
    var usrId = $(this).attr("id").split("-")[1];
    $(this).html("<a href='" + $(".hoverCardActionContainer a:first-child").attr('href') + "?open=3'>Show more</a>");
    $(".sharedConnectionsContainer").animate({
        height: "260px"
    }, 0);

    $.get("/People/GetSharedConnections", {
        userId: usrId,
        pageSize: 0
    }, function (response) {
        $('.sharedConnectionsContainer').html(response);
        if (!isIe7()) {
            $("#mcs10_container").mCustomScrollbar("vertical", 400, "easeOutCirc", 1.05, "auto", "yes", "yes", 10);
        }
    });
};

function getMoreEvents(moreButton, diaryCategory, currentPageNumber) {
    $.get("/Event/GetUpcoming", {
        page: currentPageNumber,
        diaryCategory: diaryCategory
    }, function (response) {
        insertNewItems(moreButton, response);
        reconnectAddThis();
    });
}


function postToPaging(moreButton, context, currentPageNumber) {
    var params = context.split(":");
    var action = "GetUsers" + params[2];
    if (params[1] == "Event") {
        action = "GetInvitees";
    }
    $.post("/" + params[1] + "/" + action, {
        response: params[2],
        groupId: params[3],
        page: currentPageNumber
    }, function (response) {
        insertNewItems(moreButton, response);
    });
}

function insertNewItems(moreButton, newData) {
    var newStuff = $('<div>' + newData + '</div>');
    var selContacts = $('#selectedContacts').html();
    if (selContacts != null && selContacts.substr(0, 3) == 'ALL') {
        newStuff.find('.card').removeClass('card').addClass('cardSelected');
    }
    moreButton.before(newStuff.html());
    moreButton.children('.seeMoreLink').show();
    moreButton.find('.moreLoader').hide();
    var c = newStuff.find('.feedItem').length;
    var newCount = $('#numberOfNetworkActivityPostsDisplayed');
    if (newCount != null) {
        newCount.html((c + parseInt(newCount.html())));
    }
    if ($('#LastPage').length) {
        moreButton.hide();
        $('#LastPage').remove();
    }
}

function incrementNumber(entity) {
    if (entity.html() == null) return false;
    var left = entity.html().split('(');
    if (left.length != 2) return false;
    var right = left[1].split(')');
    if (left.length != 2) return false;
    entity.html(left[0] + '(' + (parseInt(right[0]) + 1) + ')' + right[1]);
    return true;
}
    
function notifyUser(msg, duration) {
    $('#messageBar').html(msg);
    var reposition = (($(window).scrollTop()) - 5);
    $("#messageBar").css({ "position" : "fixed", "top" : "0", "left" : "0"}); /* Stick to top */
    var t = setTimeout("$('#messageBar').fadeIn(600)", 500);
    var t = setTimeout("$('#messageBar').fadeOut(1300)", 2500);		
}

function resizeMessageWindow(currentQty) {

    var initialHeight = 381;
    var innerWindowOffset = 30;
    var newQty = parseInt(currentQty);
    var rows = Math.ceil((newQty + 2) / 4);
    if (rows == 0) {
        rows = 1;
    }
    var heightAddition = ((rows - 1) * 30);

    var currentMessgeWindowHeight = $('#messageWindow').height();
    var newCurrentMessgeWindowHeight = heightAddition + initialHeight;

    if (rows > 1) {
        $('#messageWindow').animate({
            height: newCurrentMessgeWindowHeight
        }, 0, function () {
            $('#messageWindowOverlay').animate({
                height: (newCurrentMessgeWindowHeight - innerWindowOffset)
            }, 0, function () {
            });
        });
    }
}

function updateSelectedContacts() {
   
    var newString = '';
    var msg = '';
    i = 0;

    $('.cardSelected').each(function (index) {
        idParts = $(this).attr('id').split("-")
        newString += idParts[1] + '|';

        var cardName = $(this).find('.cardName');
        var cardName = cardName.find('strong');
        if (i < 3) {
            msg += '<div class="recipient recipientAlt" id="item-' + idParts[1] + '"><div class="recipientName">' + cardName.html() + '</div><div class="recipientCloseContainer"><img src="/Images/ported/messageCenter/recipientClose.gif" class="closeDisplay"></div></div>';
        }
        i++;
    });

    if (i > 3) {
        msg += '<a href="" class="standard others"> and (' + (i - 3) + ') others..</a>';
    }
    $('#selectedContactsCount').html(i);
    $('#selectedContacts').html(newString);
    $('#selectedVisualDisplay').show();
    $('#selectedVisualDisplay').html(msg);


}

function bubbleUp(startingPoint, selector) {
		
    $('#pauseFeed').val('1');
    var parentItem = startingPoint.parent();
    if (parentItem.attr('class') == selector) {

        postContainer = parentItem.next('div');
        postContainer.show();
        replyDiv = parentItem.next('div');
        imageDiv = replyDiv.find('.feedImageSmall');
        mytextArea = postContainer.find('.replyNonFocused');
        postReplyToolsDiv = postContainer.find('.postReplyTools');
				inlinePostToolbar = postContainer.find('.inlinePostToolbar');
        mytextArea.next('.closeReplyPost').show();
        mytextArea.animate({
            height: '50px',
            easing: 'linear'
        }, 0, function () {
            // Animation complete.
        });

        //mytextArea.css('height','70px');
        mytextArea.css('color', '#000');
        mytextArea.css('margin-left', '0px');
        mytextArea.html('');
        mytextArea.focus();
        imageDiv.show();
        postReplyToolsDiv.show();
        inlinePostToolbar.show();

    } else {
        bubbleUp(parentItem, selector);
    }
}

function resetSuggestion() {
    $('#recipientSuggestions').hide();
    $('.messageToHidden').val('');
    $('.messageToHidden').focus();
}

function resetContext(){
    $('#selectedVisualDisplay').html('');
    $("#selectedVisualDisplay").hide();
    $('.cardSelected').removeClass('cardSelected').addClass('card');
    $('#postContext').val('Contacts');
    $('#selectedIds').val('');
    $('#chosenContext').html('All contacts');
    $('#lastContext').html('All Contacts');
    $('#messageWindow').css('background-color', '#5A95BF');
    $('.modalWindowHeader').css('background', '#5A95BF');
    $('.closeModalDialog').attr('src', '/Images/ported/common/closeButtonInverted.gif');
}

function collapseAllAttachmentWindows(){
    $('#uploadTools, #linkTools, #videoTools, #audioTools, .commentUploadTools, #commentVideoTools, .commentAudioTools, #commentLinkTools, .closeReplyPost').hide();
    $('.replyNonFocused').css('height','28px');
    $('.replyNonFocused').css('width','310px');//324
    $('.replySimulatedContainer').css('height', '35px');//67
    $('#selectedVisualDisplay').html('');
    $("#selectedVisualDisplay").hide();
    
}

function resetItems() {
    $('.itemSuggestions').hide();
    $('.suggestableHidden').val('');
    $('.suggestableHidden').focus();
}

function userAlreadySelected(userid) {
    var x;
    var recipients = $('#recipientList').html();
    recipientsArray = recipients.split('|');
    for (x in recipientsArray) {
        if (recipientsArray[x] == userid) {
            return true;
        }
    }
    return false;
}

function spawnModalMessage(){
    $.post("/Campaign/RenderCampaign", function (response) {
        if (response != '0') {
            $('.modalHeader').html('Import Your Contacts');
            var reposition = (($(window).scrollTop()) + 45);

            $('#emptyModalDialogue').css('margin-top', reposition + 'px');
            $('#emptyModalDialogue').css('width', '670px');
            $('#emptyModalWindowBody').css('width', '610px');
            $('#emptyModalWindow').css('width', '670px');
            $('#emptyModalWindow').css('height', '503px');
            $('#emptyModalWindowOverlay').css('width', '640px');
            $('#emptyModalWindowOverlay').css('height', '473px');
            $('.modalHeader').css('width', '80%');
            $('#emptyModalDialogue').show();
            $('.modalInstructionMessage').html('instruction message');
            $('#emptyModalWindowBody').html(response);
            $("#emptyModalDialogue").draggable({ handle: '.modalHeader' });
            //$('#spawnModalMessage').html('')
        } else {
            //$('#emptyModalWindowBody').html('no campiagn');
            //$('#spawnModalMessage').html('')
        }
    });

}

function fillCommentAttachment(response, linkPreview, id) {
    
    linkPreview.show();
    var linkPreviewTitle = linkPreview.find('.linkPreviewTitle');
    var totalImages = linkPreview.find('.totalImages');
    var linkPreviewUrl = linkPreview.find('.linkPreviewUrl');
    var linkPreviewIntro = linkPreview.find('.linkPreviewIntro');
    var linkPreviewImage = linkPreview.find('.linkPreviewImage');
    var thumbnailController = linkPreview.find('.thumbnailController');

    var hiddenLinkThumbnail = linkPreview.find('#hiddenLinkThumbnail-' + id);
    var hiddenLinkTitle = linkPreview.find('#hiddenLinkTitle-' + id);
    var hiddenLinkIntro = linkPreview.find('#hiddenLinkIntro-' + id);
    var hiddenLinkUrl = linkPreview.find('#hiddenLinkUrl-' + id);

    var pageImageString = '';

    pageImages = response.ImageUrls;
    for (var i in pageImages) {
        pageImageString += '<div class="linkImageHolder"><img src="' + pageImages[i] + '" /></div>';
    }

    linkPreviewTitle.html(response.Title);

    totalImages.html(response.NumberOfImagesFound);
    linkPreviewUrl.html('<strong>Shortened Url: </strong><a href="' + response.ShortenedUrl + '">' + response.ShortenedUrl + '</a>');
    linkPreviewIntro.html('<p class="small">' + response.Summary + '</p>');
    linkPreviewImage.html(pageImageString);
    thumbnailController.fadeIn(200);

    var previewImageDiv = $('div[id|="linkPreviewImage"] img:nth-child(1)');
    hiddenLinkThumbnail.val(previewImageDiv.attr('src'));
    hiddenLinkTitle.val(response.Title);
    hiddenLinkIntro.val(response.Summary);
    hiddenLinkUrl.val(response.ShortenedUrl);

    notifyUser('Thank you, your link now attached to this post.');
}

function fillLinkAttachment(response) {
		
    $('#linkPreview').show();
    $('#linkShare').show();

    var pageImageString = '';

    pageImages = response.ImageUrls;
    for (var i in pageImages) {
        pageImageString += '<div class="linkImageHolder linkImageWindowLarge"><img height="121" src="' + pageImages[i] + '" /></div>';
    }

    $('#linkPreviewTitle').html(response.Title);
    //$('#totalImages').html(response.NumberOfImagesFound);
    $("#totalImagesLink").html(response.NumberOfImagesFound);
    //alert('setting number to '+response.NumberOfImagesFound);
    $("#currentImageLink").html("1"); //Added
    $('#linkPreviewUrl').html('<strong>Shortened Url: </strong><a href="' + response.ShortenedUrl + '">' + response.ShortenedUrl + '</a>');
    $('#linkPreviewIntro').html('<p class="small">' + response.Summary + '</p>');
    $('#linkPreviewImage').html(pageImageString);
    $('#thumbnailController').fadeIn(200);
    $("#linkPreviewImageWindow").show();

    var previewImageDiv = $('div[id|="linkPreviewImage"] img:nth-child(1)');
    $('#hiddenLinkThumbnail').val(previewImageDiv.attr('src'));
    $('#hiddenLinkTitle').val(response.Title);
    $('#hiddenLinkIntro').val(response.Summary);
    $('#hiddenLinkUrl').val(response.ShortenedUrl);

    if (response.NumberOfImagesFound <= 0) {
        $("#thumbnailController").hide();
    } else {
        $("#thumbnailController").show();
    }

    notifyUser('Thank you, your link now attached to this post.');
}

$(function () {

    var stop = false;
    $("#accordion h3").click(function (event) {
        if (stop) {
            event.stopImmediatePropagation();
            event.preventDefault();
            stop = false;
        }
    });

    var icons = {
        header: "accordionIconOpen",
        headerSelected: "accordionIconClosed"
    };

    $("#accordion").accordion({
        header: "> div > h3",
        icons: icons,
        autoHeight: false,
        animated: !isIe8orOlder(),
        collapsible: true,
        clearStyle: true,
        active: 0
    }).sortable({
        axis: "y",
        handle: "h3",
        stop: function (event, ui) {
            order = '';
            $("#accordion h3").each(function (idx, elm) {
                order += elm.id + '|';
            });

            $("#accordionSmall h3").each(function (idx, elm) {
                order += elm.id + '|';
            });

//            $.post("/Scripts/xhr/layoutControl.aspx", {
//                'accordionLayout': order
//            }, function (response) {

//                $(".lastAccordion").removeClass('lastAccordion');
//                $("#accordion h3:lastChild").addClass('lastAccordion');

//                /* notifyUser('Layout changes saved for your profile.'); */
//            });

            stop = true;
        }
    });

    $("#accordionSmall").accordion({
        header: "> div > h3",
        animated: !isIe8orOlder(),
        icons: icons,
        autoHeight: false,
        navigation: true,
        collapsible: true,
        clearStyle: true,
        active: 2

    }).sortable({
        axis: "y",
        handle: "h3",
        stop: function (event, ui) {
            order = '';
            $("#accordion h3").each(function (idx, elm) {
                order += elm.id + '|';
            });

            $("#accordionSmall h3").each(function (idx, elm) {
                order += elm.id + '|';
            });

//            $.post("/Scripts/xhr/layoutControl.aspx", {
//                'accordionLayout': order
//            }, function (response) {
//                /*notifyUser('Layout changes saved for your profile.');*/
//            });
            stop = true;
        }
    });
});

$(function () {
    $(".column").sortable({
        connectWith: '.column',
        cursor: 'crosshair',
        opacity: 0.7,
        revert: 200,
        stop: function (event, ui) {

            order = '';
            $(".column .portlet").each(function (idx, elm) {
                order += $(this).attr('id') + '|';
            });

            //            $.post("/Scripts/xhr/layoutControl.aspx", {
            //                'portletLayout': order
            //            }, function (response) {
            //                /* notifyUser('Layout changes saved for your profile.'); */
            //            });
            stop = true;
        }
    });

    $(".portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
			.find(".portlet-header")
				.addClass("ui-widget-header ui-corner-all")
				.prepend('<span class="ui-icon ui-icon-minusthick"></span>')
				.end()
			.find(".portlet-content");

    $(".portlet-header .ui-icon").click(function () {
        $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
        $(this).parents(".portlet:first").find(".portlet-content").toggle();
    });

    $(".column").disableSelection();
});


$(document).ready(function () {
    //disable sortable sidebar until it does something useful

    if (isIe7) {
        $("a").focus(function () {
            this.hideFocus = true;
        });
    }

    $(".column").sortable("disable");

    $('.skipCurrentCampaign').live('click', function () {
        $.post("/Campaign/RegisterSkip", {
            id: $('.campaignId').html()
        }, function (response) {
            $('#emptyModalDialogue').hide();
        });
    });

    $('.ignoreCurrentCampaign').live('click', function () {
        $.post("/Campaign/RegisterIgnore", {
            id: $('.campaignId').html()
        }, function (response) {
            $('#emptyModalDialogue').hide();
        });
    });

    $('.clickCurrentCampaign').live('click', function () {
        $.post("/Campaign/RegisterClick", {
            id: $('.campaignId').html()
        }, function (response) {
            $('#emptyModalDialogue').hide();
        });
    });

    var windowWidth = $(window).width();
    if (windowWidth < 1025) {
        $('.floatingNavItemContainer').css('width', '60px');
        $('.floatingNavItemContainer').animate({
            marginLeft: '-42'
        }, 0, function () {
        });

        $('.floatingNavItemContainer').live('click', function () {
            $('.floatingNavItemContainer').animate({
                marginLeft: '0'
            }, 500, function () {
            });
        });

        $('#fdbk_tab').mouseleave(function () {
            $('.floatingNavItemContainer').animate({
                marginLeft: '-42'
            }, 500, function () {

            });
        });
    }

    $('.welcomeGroup').live('mouseover', function () {
        var joinGroupIcon = $(this).find('.joinGroup');
        joinGroupIcon.show();
    });

    $('.welcomeGroup').live('mouseleave', function () {
        var joinGroupIcon = $(this).find('.joinGroup');
        joinGroupIcon.hide();
    });

    $('.joinGroup').live('mouseover', function () {
        var maxiSpeechIcon = $(this).find('.maxiSpeechIcon');
        maxiSpeechIcon.show();
    });

    $('.joinGroup').live('mouseleave', function () {
        var maxiSpeechIcon = $(this).find('.maxiSpeechIcon');
        maxiSpeechIcon.hide();
    });

    $('object, .video').live('focus', function () {
        pauseNetworkActivityFeed();
    });


    /* start event related javascript */

    $('#addEventDescription').live('click', function () {
        $('#eventDescriptionContainer').toggle();
    });

    $('#editGroupForm input#Name').keyup(function () {
        codeLength = $('input#Name').val().length;
        if (codeLength > 3) {
            $.post("/Group/GetAvailableGroupNameSlug", {
                groupName: $('input#Name').val(),
                groupId: $('input#Id').val()
            }, function (response) {
                $('#GroupNameSlug').val(response);
            });
        } else {
            $('#GroupNameSlug').val('');
        }
    });

    $('#eventPostcodeContainer #Postcode').live('keyup', function () {
        codeLength = $('#eventPostcodeContainer #Postcode').val().length;

        if (codeLength > 2) {
            var the_char = parseInt($('#eventPostcodeContainer #Postcode').val().charAt(0));
            if (is_int(the_char)) {
                /* US */
                $('#detectedLocale').html('US');
            } else {
                /* UK */
                $('#detectedLocale').html('UK');
            }

            mapLoad();
            $('#eventMapInline').slideDown();
        }

        if (codeLength < 2) {
            $('#eventMapInline').slideUp();
        }
    });

    $('#addEventImage').live('click', function () {
        $('#eventLogoContainer').toggle();
        return false;
    });

    $('#addEventType').live('click', function () {
        $('#eventTypeContainer').toggle();
        return false;
    });

    $('#addEventTime').live('click', function () {
        $('#startTimeContainer, #endTimeContainer, #timeZoneContainer, #endDateContainer, #stopDateContainer').toggle();
        return false;
    });

    $('#addEventTags').live('click', function () {
        $('#eventTagContainer').toggle();
        return false;
    });

    $('#addEnablePublicProfile').live('click', function () {
        $('#eventEnablePublicProfileContainer').toggle();
        return false;
    });

    $('#addEventLink').live('click', function () {
        $('#eventLinkContainer').toggle();
        return false;
    });

    $('#addEventAddress').live('click', function () {
        $('#eventStreetContainer,, #eventCityContainer, #eventPostcodeContainer, #eventMapContainer').toggle();
        return false;
    });

    $('#EventEndDate').live('click', function () {
        $(this).focus();
        $(this).select();
    });

    $('#EventStartDate, #EventEndDate').live('blur', function () {
        var enteredDate = $(this).val();
        var parsedDate = Date.parse(enteredDate);
        if (parsedDate != null) {
            var curVal = parsedDate.toString();
            var dateParts = curVal.split(" ");
            var yearIndex = dateParts[3] == "00:00:00" ? 5 : 3; // ie
            $(this).val(dateParts[0] + ', ' + dateParts[1] + ' ' + dateParts[2] + ' ' + dateParts[yearIndex]);
        } else {
            var enteredDateParts = $(this).val().split(" ");
            if (enteredDate == 'the morra') {
                enteredDate = 'tomorrow';
                parsedDate = Date.parse(enteredDate);
                var curVal = parsedDate.toString();
                var dateParts = curVal.split(" ");
                var yearIndex = dateParts[3] == "00:00:00" ? 5 : 3; // ie
                $(this).val(dateParts[0] + ', ' + dateParts[1] + ' ' + dateParts[2] + ' ' + dateParts[yearIndex]);
            } else if (enteredDateParts[0] + ' ' + enteredDateParts[1] + ' ' + enteredDateParts[2] == 'a week on') {
                var enteredDate = enteredDateParts[3] + ' week';
                var parsedDate = Date.parse(enteredDate);
                var curVal = parsedDate.toString();
                var dateParts = curVal.split(" ");
                var yearIndex = dateParts[3] == "00:00:00" ? 5 : 3; // ie
                $(this).val(dateParts[0] + ', ' + dateParts[1] + ' ' + dateParts[2] + ' ' + dateParts[yearIndex]);
                //} else if (enteredDateParts[1] + ' ' + enteredDateParts[2] == 'weeks on') {
                //TODO - looks like the above isn't finished!
            } else {
                if (enteredDate != '') {
                    notifyUser("Sorry, I didn't understand the date you entered, please try again.");
                    $(this).val('');
                }
            }
        }
        if (parsedDate != null) {
            var newDateVal = $(this).val();
            if ($(this).attr('id') == 'EventStartDate') {
                if ($('#EventEndDate').val() == '' || parsedDate > Date.parse($('#EventEndDate').val())) {
                    $('#EventEndDate').val(newDateVal);
                }
            } else if (parsedDate < Date.parse($('#EventStartDate').val())) {
                notifyUser('Sorry, the event cannot end before it starts!');
                $('#EventEndDate').val($('#EventStartDate').val());
            }
            $('#endDateContainer, #startTimeContainer, #endTimeContainer, #timeZoneContainer, #stopDateContainer').show();
        }
    });

    /* end event related javascript */

    var currentIndex = 0;

    $(document).keypress(function (event) {

        var distance = 130;
        var offset = 26;
        activeObj = document.activeElement;
        if (activeObj.tagName == "BODY") {
            if (event.keyCode == 38) {
                var currentFocus = document.activeElement;
                pagingValue = 6;
                event.preventDefault();

                if (currentIndex > 1) {

                    currentIndex -= 1;
                    var currentPage = currentIndex / pagingValue;

                    $('.dropdownItemCursorOver').removeClass('dropdownItemCursorOver');
                    $('.dropdownLarge li:nth-child(' + currentIndex + '), .dropdownMedium li:nth-child(' + currentIndex + '), .dropdown li:nth-child(' + currentIndex + ')').addClass('dropdownItemCursorOver');
                    if (is_int((currentIndex + 1) / pagingValue)) {
                        var distance = 130;

                        if ((currentIndex + 1) == pagingValue) {
                            var newPos = ((((currentIndex + 1) / pagingValue) * distance) - distance);
                        } else {

                            var newPos = ((((currentIndex + 1) / pagingValue) * distance) - distance) + ((currentPage - 2) * offset);
                        }

                        $('.dropdownLarge, .dropdown, .dropdownMedium').scrollTo(newPos, 800);
                    }

                } else {
                    currentIndex = 1;
                }



            } else if (event.keyCode == 40) {

                pagingValue = 6;
                event.preventDefault();

                currentIndex += 1;
                var currentPage = currentIndex / pagingValue;

                $('.dropdownItemCursorOver').removeClass('dropdownItemCursorOver');
                $('.dropdownLarge li:nth-child(' + currentIndex + '),.dropdownMedium li:nth-child(' + currentIndex + '), .dropdown li:nth-child(' + currentIndex + ')').addClass('dropdownItemCursorOver');

                if (is_int(currentIndex / pagingValue)) {
                    var distance = 130;
                    if (currentIndex == pagingValue) {
                        var newPos = ((currentIndex / pagingValue) * distance);
                    } else {
                        var newPos = (((currentIndex / pagingValue) * distance) + ((currentPage - 1) * offset));
                    }
                    $('.dropdownLarge, .dropdownMedium, .dropdown').scrollTo(newPos, 800);
                }
            }
        }
    });

    $('#switchSides').live('click', function () {

        if ($('#primaryContent').css('float') == 'left') {
            $('#primaryContent').css('margin-right', '0px');
            $('#primaryContent').removeClass('floatLeft').addClass('floatRight');
            $('#rightColumn').removeClass('floatRight').addClass('floatLeft');
            /*
            $('#primaryContent').css('float','right');
            $('#rightColumn').css('float','left');
            */
            $('#rightColumn').css('margin-right', '50px');
            //            $.post("/Scripts/xhr/layoutControl.aspx", {
            //                'sideSwitcher': 'switch-rightleft'
            //            }, function (response) {
            //                notifyUser('Layout changes saved for your profile.');
            //            });

        } else {

            $('#primaryContent').css('margin-right', '50px');
            $('#rightColumn').removeClass('floatLeft').addClass('floatRight');
            $('#primaryContent').removeClass('floatRight').addClass('floatLeft');

            //            $.post("/Scripts/xhr/layoutControl.aspx", {
            //                'sideSwitcher': 'switch-leftright'
            //            }, function (response) {
            //                notifyUser('Layout changes saved for your profile.');
            //            });
            /*
            $('#rightColumn').css('float','right');
            $('#primaryContent').css('float','left');
            */
            $('#rightColumn').css('margin-right', '0px');
        }

    });


    $('.shareItemLink').live('click', function () {
        var actionIdParts = $(this).attr('id').split('-');
        if (actionIdParts[0] == "group") {
            $.post("/Ajax/CreateGroupRecommendationNotification", {
                groupId: actionIdParts[2]
            }, function (response) {
                notifyUser('This has been posted to your activity feed.');
            });
        }
        return false;
    });

    $('.reportLink').live('click', function () {
        var reposition = (($(window).scrollTop()) + 45);
        $('#message').css('margin-top', reposition + 'px');
        $('#message').show();
        $("#message").draggable({ handle: '.modalHeader' });
        var actionIdParts = $(this).attr('id').split('-');
        var replacementText = '';
        var currentStorageValue = $('#inputStorage').val();
        var senderId = $('.messageFrom').attr('id');
        var fromName = $('#fromName').html();
        $('.recipient').remove();
        $('.suggestableHidden').before('<div class="recipient" id="recipient-10005"><div class="recipientName">report@kiltr.com</div><div class="recipientCloseContainer"><img src="/Images/ported/messageCenter/recipientClose.gif" class="recipientClose"></div></div>');
        $('#messageSubject').val('Report: ' + actionIdParts[0] + ' ' + actionIdParts[2]);
        $('#messageBody').val('Please tell us the reasons why you would like to report this to KILTR and we\'ll look into it. Thank you for your feedback and helping us to keep KILTR a trusted and safe environment.\n\nThe KILTR team\n' + replacementText);
        $('.inputStorage').val(10005);
        styleReportWindow();
        return false;
    });

    $('.ui-accordion-header').live('click', function () {

        var parent = $(this).parent();
        var parent = parent.parent();

        if (parent.attr('id') == 'accordion') {
            $(this).find(":last-child").css('color', '#5A95BF');
            var offset = $(this).offset().top;
            var curId = $(this).attr('id');
            var active = $("#accordion").accordion("option", "active");
            var inputBox = $('#postBody').attr('id');
            /* updated logic to determine first accordion header position regardless of page or start position */
            var accord = $('.ui-accordion-header:first');
            var offset = accord.offset();
            pageOffset = (parseInt(offset.top) - 75);
            var destination = (pageOffset + (active * 31));

            if (!isIe8orOlder()) {
                if (active != 0) {
                    $.scrollTo(destination, 1500);
                } else {
                    $.scrollTo(0, 1500);
                }
            }
        }

    });

    $('#accordionLock').live('click', function () {
        if ($(this).hasClass('locked')) {
            setAutoScroll($('.seeMoreItems.noAutoLoad'), true);
            $(this).attr('class', 'unlocked');
        }
        else {
            setAutoScroll($('.seeMoreItems'), false);
            $(this).attr('class', 'locked');
        }
    });

    $('#moreButton').live('mouseover', function () {
        $('#moreOptions').toggle();
        $('#navContainer, #publicNav').css('background', 'url(/Images/ported/common/primaryNavBack.jpg) 375px 30px no-repeat');
    });

    $('.seeMoreItems').live('click', function () {
        //if ($(this).attr('id').match(/^NetworkActivityFeed:(Public|MyKiltr)/)) {
        setAutoScroll($(this), true);
        //}
        loadMore($(this));
    });

    $(window).scroll(function () {
        pageOnScroll();
    });

    $('.cardPicker').scroll(function () {
        pageOnScroll();
    });

    $(window).keydown(function (ev) {
        justPressedEnd = false;
        if (ev.keyCode == 35) {
            justPressedEnd = true;
        }
    });

    function pageOnScroll() {
        if ($('.seeMoreItems.noAutoLoad:visible').html() != null || $('.seeMoreItems:visible').find('.moreLoader').is(':visible')) {
            return false;
        }

        if (isScrolledIntoView($('.seeMoreItems:visible'))) {
            loadMore($('.seeMoreItems:visible'));
        }
    }

    function isScrolledIntoView(elem) {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();
        var elemOffset = $(elem).offset();
        if (elemOffset == null)
            return false;
        var elemTop = elemOffset.top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
    }

    $('#moreOptions').live('mouseleave', function () {
        $('#moreOptions').hide();
        $('#navContainer').css('background-image', 'none');
    });

    $('#searchTypeSelectorArrow').live('click', function () {
        $('#searchOptions').toggle();
        $('#searchTypeLabel').css('color', '#123A59');
    });

    $('#searchOptions').live('mouseleave', function () {
        $('#searchOptions').hide();
        $('#searchTypeLabel').css('color', '#8F9599');
    });

    $('.searchOption').live('click', function () {

        var parentDiv = $(this).parent();
        var parentDiv = parentDiv.parent();

        var searchType = $(this).html();
        if (parentDiv.attr("id") != "moreOptions") {
            $('#searchTypeLabel').html(searchType);
            $('#selectedSearchOption').val($(this).attr('id'));
        }

        $('#searchOptions').hide();
    });


    $('#addImage').click(function () {
        collapseAllAttachmentWindows();
        $('#closeCreatePost').show();
        $('#uploadTools').slideDown(0, function () {
            $('#folderTools').fadeIn(0);
            $('#browseTools').fadeIn(0);
        });
    });

    $('.addImageToComment').live('click', function () {

        parentDiv = $(this).parent().parent().parent().parent();
        hinge = parentDiv.parent();
        idParts = hinge.attr('id').split('-');

        pauseNetworkActivityFeed();
        collapseAllAttachmentWindows();

        $('.closeReplyPost').show();

        $('#icons>.iconAction').css('background-position', '0px -62px');
        $('#icons li').css('background-position', '');
        $(this).css('background-position', '0px 0px');
        $(this).css('background-position', '0px 0px');
        //hinge.find('.iconAction').css('background-position','0px -30px');

        var container = hinge.find('.replySimulatedContainer');
        container.find('.closeReplyPost').show();

        $('#linkFormTools').css('margin-top', '-1px');
        //hinge.find('.replySimulatedContainer').css('border', '1px solid #5393BF');
        hinge.find('.replySimulatedContainer').css('height', '88px');
        hinge.find('.replySimulatedContainer').css('margin-left', '0px');
        hinge.find('.replyNonFocused').css('width', '410px'); //445 then 324
        hinge.find('.replyNonFocused').css('height', '50px');
        hinge.find('.icons').css('margin', '5px 5px 0px 0px');
        hinge.find('.postReplyTools').show();
        $(this).parent().parent().parent().parent().find('.feedImageSmall').show();

        /*
        $('#linkFormTools').css('margin-top','-1px');
        $('.replySimulatedContainer').css('border','1px solid #5393BF');
        $('.replySimulatedContainer').css('height','88px');
        $('.replySimulatedContainer').css('margin-left','0px');
        */

        commentAreaBottom = parentDiv.next('div');
        curCookieContainer = commentAreaBottom.next('div');
        curCookieVal = curCookieContainer.html();

        if (parseInt($('#attachmentWindowStatus-' + idParts[1]).html()) == 0) {

            $.post("/Scripts/xhr/getCommentAttachmentDevice.aspx", {
                postId: idParts[1],
                cookieVal: curCookieVal
            }, function (response) {

                $('#attachmentWindowStatus-' + idParts[1]).html(1);

                commentAreaBottom.html(response);
                var uploadToolsDiv = commentAreaBottom.find('.commentUploadTools');
                var folderTools = commentAreaBottom.find('.folderTools');
                var browseTools = commentAreaBottom.find('.browseTools');
                uploadToolsDiv.slideDown(0, function () {
                    folderTools.show();
                    browseTools.show();
                });
            });
        } else {

            uploadToolsDiv = commentAreaBottom.find('.commentUploadTools');
            folderTools = commentAreaBottom.find('.folderTools');
            browseTools = commentAreaBottom.find('.browseTools');

            uploadToolsDiv.slideDown(0, function () {
                folderTools.show();
                browseTools.show();
            });
        }

        /*commentAreaBottom*/


    });

    $('#uploadToolsClose').live('click', function () {
        $(this).parent().hide();
    });

    function GetAttachmentPrompt(clickedIcon) {
        if (clickedIcon.attr('id') == 'addLink') return 'Paste your link url here: (e.g. http://www.kiltr.com or Video / Audio)';
        if (clickedIcon.attr('id') == 'addAudio') return 'Paste your SoundCloud or MixCloud Url below:';
        if (clickedIcon.attr('id') == 'addVideo') return 'Paste your Vimeo, YouTube or Livestream url below:';
    }


    $('#linkUrl').keypress(function (event) {

        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            AddAttachment();
            event.stopPropagation();
            return false;
        }
    });


    var lastClicked = "";

    function HandleAttachments() {
        $("#closeCreatePost").show();
        $('#contextBar').show();
        var attachmentBackground = $(this).parent().parent().parent().parent().parent().find('#linkFormTools');
        switch ($(this).attr('class')) {

            case 'addLinkToPost iconAction':
                attachmentBackground.css('background', 'url("/Images/kiltr_v2/feed/commentLinkAttachmentBackgr.gif") no-repeat 0 7px transparent');
                break;

            case 'addAudioToPost iconAction':
                attachmentBackground.css('background', 'url(/Images/kiltr_v2/feed/commentAudioAttachmentBackg.gif)');
                break;

            case 'addVideoToPost iconAction':
                attachmentBackground.css('background', 'url(/Images/kiltr_v2/feed/commentVideoAttachmentBackg.gif)');

                break;

            default:
                //attachmentBackground.css('background', 'url("/Images/kiltr_v2/feed/commentLinkAttachmentBackgr.gif") no-repeat 0 7px transparent');
        }


        var hinge = $(this).parent().parent().parent().parent().parent();
        var icon = $(this);
        var container = hinge.find('.replySimulatedContainer');
        var newContainer = hinge.find('#StatusUpdate-form');

        var commentAreaBottom = $(this).parent().parent().parent().parent().next('.commentAreaBottom');
        var curCookieContainer = commentAreaBottom.next('div');
        var curCookieVal = curCookieContainer.html();
        var idParts = hinge.attr('id').split('-');

        $('#icons>.iconAction').css('background-position', '0px -62px');
        $('#icons li').css('background-position', '');
        /*
        hinge.find('.iconAction').css('background-position','0px -30px');
        */
        $(this).css('background-position', '0px 0px');

        $('#linkFormTools').css('margin-top', '-1px');

        container.css('border', '1px solid #5393BF');
        container.css('height', '88px');
        container.css('margin-left', '0px');

        //newContainer.css('height','235px');

        hinge.find('.replyNonFocused').css('width', '410px'); //518
        hinge.find('.replyNonFocused').css('height', '50px');
        hinge.find('.icons').css('margin', '0px 5px 0px 0px');

        $(this).parent().parent().parent().parent().find('.feedImageSmall').show();
        hinge.find('.postReplyTools').show();
        //$('#postBody').css('height', '108px');
        $('#postBody').css('width', '545px');
        //        $('#linkTools').slideDown(0, function () {
        //            $('#linkFormTools').fadeIn(1000);
        //        });
        collapseAllAttachmentWindows();
        $("#linkTools").show();
        //        $("#linkFormTools").show();
        if (parseInt($('#attachmentWindowStatus-' + idParts[1]).html()) == 0) {

            $.post("/Scripts/xhr/getCommentAttachmentDevice.aspx", {
                postId: idParts[1],
                cookieVal: curCookieVal
            }, function (response) {
                $('#attachmentWindowStatus-' + idParts[1]).html(1);
                commentAreaBottom.html(response);
                $('.commentUploadTools').hide();
                linkToolsDiv = commentAreaBottom.find('.linkToolsDiv');
                linkToolsForm = linkToolsDiv.find('#linkFormTools');
                linkToolsForm.find('.onTop').html(GetAttachmentPrompt(icon));
                linkToolsDiv.slideDown(0, function () {
                    linkToolsForm.show();
                });
            });
        } else {
            $('.commentUploadTools').hide();
            linkToolsDiv = commentAreaBottom.find('.linkToolsDiv');
            linkToolsForm = linkToolsDiv.find('#linkFormTools');
            linkToolsForm.find('.textbox').val('');

            //Hack!!!
            if ($(this).hasClass("addLinkToPost")) {
                //$("#linkUrl").attr("placeholder", "Type or paste a link");
                $("#linkUrl").val("Type or paste a link");
                $("#linkFormTools").css('background', 'url("/Images/kiltr_v2/feed/commentLinkAttachmentBackgr.gif") no-repeat 0 7px transparent');
                $('#videoTools,#videoPreview').hide();
                $("#audioTools").hide();
                if ($("#linkPreviewTitle").html() != "") {
                    $('#linkPreview').show();
                    $("#linkFormTools").hide();
                    $("#linkToolsClose").show();
                    $("#videoToolsClose, #audioToolsClose").hide();
                } else {
                    $("#linkFormTools").show();
                    $('#linkPreview').hide();
                    $("#videoToolsClose, #linkToolsClose, #audioToolsClose").hide();
                }
            }

            if ($(this).hasClass("addVideoToPost")) {
                //                $("#linkUrl").attr("placeholder", "Type or paste your Vimeo, YouTube or Livestream URL");
                $("#linkUrl").val("Type or paste your Vimeo, YouTube or Livestream URL");
                $("#linkFormTools").css('background', 'url("/Images/kiltr_v2/feed/commentVideoAttachmentBackg.gif") no-repeat 0 7px transparent');
                $('#linkPreview').hide();
                $("#audioTools").hide();
                if ($("#videoPreview object").length > 0) {
                    $('#videoTools,#videoPreview').show();
                    $("#linkFormTools, #linkTools").hide();
                    $("#videoToolsClose").show();
                    $("#linkToolsClose, #audioToolsClose").hide();
                } else {
                    $("#linkFormTools").show();
                    $('#videoTools,#videoPreview').hide();
                    $("#videoToolsClose, #linkToolsClose, #audioToolsClose").hide();
                }
            }

            if ($(this).hasClass("addAudioToPost")) {
                //$("#linkUrl").attr("placeholder", "Type or Paste your SoundCloud or MixCloud URL");
                $("#linkUrl").val("Type or Paste your SoundCloud or MixCloud URL");
                $("#linkFormTools").css('background', 'url("/Images/kiltr_v2/feed/commentAudioAttachmentBackg.gif") no-repeat 0 7px transparent');
                $('#linkPreview').hide();
                $('#videoTools,#videoPreview').hide();
                if ($("#audioPreview object").length > 0) {
                    $('#audioTools').show();
                    $("#linkFormTools, #linkTools").hide();
                    $("#audioToolsClose").show();
                    $("#linkToolsClose, #videoToolsClose").hide();
                } else {
                    $("#linkFormTools").show();
                    $('#audioTools').hide();
                    $("#videoToolsClose, #linkToolsClose, #audioToolsClose").hide();
                }
            }

            linkToolsForm.find('.onTop').html(GetAttachmentPrompt(icon));
            linkToolsDiv.slideDown(0, function () {
                linkToolsForm.fadeIn(1000);
            });
        }

        //if ($(this).hasClass('addLinkToPost')) {
        $('#linkPrompt').html(GetAttachmentPrompt($(this)));

        lastClicked = $(this).attr("class");

        //$('#linkUrl').val('');
        //$('#linkPreview').hide();
        //        $('#linkTools').slideDown(0, function () {
        //            $('#linkFormTools').fadeIn(1000);
        //        });
        //}
    }

    $("#linkUrl").blur(function () {
        if ($(this).val() == "") {
            switch (lastClicked) {
                case "addLinkToPost":
                    $(this).val("Type or paste a link");
                    break;
                case "addVideoToPost":
                    $(this).val("Type or paste your Vimeo, YouTube or Livestream URL");
                    break;
                case "addAudioToPost":
                    $(this).val("Type or Paste your SoundCloud or MixCloud URL");
                    break;
            }
        }
    }).focus(function () {
        switch (lastClicked) {
            case "addLinkToPost":
                if ($(this).val() == "Type or paste a link") {
                    $(this).val("");
                }
                break;
            case "addVideoToPost":
                if ($(this).val() == "Type or paste your Vimeo, YouTube or Livestream URL") {
                    $(this).val("");
                }
                break;
            case "addAudioToPost":
                if ($(this).val() == "Type or Paste your SoundCloud or MixCloud URL") {
                    $(this).val("");
                }
                break;
        }

    });

    $(".textboxNew").live('focus', function () {
        $(this).val("");
    });

    $('#addLink.addLinkToPost, #addVideo.addVideoToPost, #addAudio.addAudioToPost').live('click', HandleAttachments);

    $('#addImage.addImageToPost').live('click', function () {
        $("#closeCreatePost").show();
    });

    $('.postTypeSwitch').live('click', function () {
        //$('.switchOn').removeClass('switchHighlighted');
        //$('.switchHighlighted').removeClass('switchHighlighted');
        $('.switchOn').removeClass('switchOn');
        resetShareBox();
        //$(this).addClass('switchHighlighted');
        //$('#StatusUpdate-form').css('border-color','#5392BE');


        $(this).addClass('switchOn');
        $('#postType').val($(this).attr('id'));

        switch ($(this).attr('id')) {

            case 'StatusUpdate':
                $('#arrowFoot').css('margin-left', '-459px');
                $('#postBody').show();
                $('#Event-form').hide();
                //$('#Job-form').hide();
                break;

            case 'AnOpportunity':
                $('#arrowFoot').css('margin-left', '-397px'); //+62
                $('#postBody').show();
                $('#Event-form').hide();
                //$('#Job-form').hide();
                break;

            case 'Event':
                $('#arrowFoot').css('margin-left', '-335px'); //+62
                $('#Event-form').show();
                $('#postBody').hide();
                //$('#Job-form').hide();
                break;

            case 'Job':
                $('#arrowFoot').css('margin-left', '-335px');
                $('#Job-form').show();
                $('#postBody').hide();
                $('#Event-form').hide();
                break;

            //            case 'Job':                              
            //                $('#arrowFoot').css('margin-left', '-273px'); //+62 (bookmark)                              
            //                $('#Job-form').show();                              
            //                $('#postBody').hide();                              
            //                $('#Event-form').hide();                              
            //                break;                              

            default:
                $('#arrowFoot').css('margin-left', '-3335px');
        }


    });

    $('.addLinkToComment, .addAudioToComment, .addVideoToComment').live('click', function () {
        pauseNetworkActivityFeed();
        collapseAllAttachmentWindows();
        var hinge = $(this).parent().parent().parent().parent().parent();


        var icon = $(this);
        var container = hinge.find('.replySimulatedContainer');
        container.find('.closeReplyPost').show();

        var commentAreaBottom = $(this).parent().parent().parent().parent().next('.commentAreaBottom');
        var curCookieContainer = commentAreaBottom.next('div');
        var curCookieVal = curCookieContainer.html();
        var idParts = hinge.attr('id').split('-');
        $('#icons>.iconAction').css('background-position', '0px -62px');
        $('#icons>.iconAction').css('color', '#00FFFF');
        $('#icons li').css('background-position', ''); //this sets the inactive tabs to default
        //hinge.find('.iconAction').css('background-position', '0px -30px'); //breaks comment reply delete button images, not deleted for fear of breaking something else
        $(this).css('background-position', '0px 0px'); //this sets the active tab to active

        $('#linkFormTools').css('margin-top', '-1px');

        //container.css('border', '1px solid #5393BF');
        container.css('height', '88px');
        container.css('margin-left', '0px');

        hinge.find('.replyNonFocused').css('width', '410px'); //445 then 324
        hinge.find('.replyNonFocused').css('height', '50px');
        hinge.find('.icons').css('margin', '5px 5px 0px 0px');

        $(this).parent().parent().parent().parent().find('.feedImageSmall').show();
        hinge.find('.postReplyTools').show();

        var selectedTypeClass = $(this).attr('class');
        //alert(selectedTypeClass);

        if (parseInt($('#attachmentWindowStatus-' + idParts[1]).html()) == 0) {

            $.post("/Scripts/xhr/getCommentAttachmentDevice.aspx", {
                postId: idParts[1],
                cookieVal: curCookieVal
            }, function (response) {
                $('#attachmentWindowStatus-' + idParts[1]).html(1);
                commentAreaBottom.html(response);
                $('.commentUploadTools').hide();
                commentAreaBottom.css('width', '532px');
                linkToolsDiv = commentAreaBottom.find('.linkToolsDiv');
                linkToolsForm = linkToolsDiv.find('#linkFormTools');
                var linkUrl = linkToolsForm.find('.textboxNew');
                linkToolsForm.find('.onTop').html(GetAttachmentPrompt(icon));
                switch (selectedTypeClass) {

                    case 'addLinkToComment':
                        linkToolsForm.css('background-image', 'url(/Images/kiltr_v2/feed/commentLinkAttachmentBackgr.gif)');
                        linkUrl.val("Type or paste a link");
                        break;

                    case 'addAudioToComment':
                        linkToolsForm.css('background-image', 'url(/Images/kiltr_v2/feed/commentAudioAttachmentBackg.gif)');
                        linkUrl.val("Type or Paste your SoundCloud or MixCloud URL");
                        break;

                    case 'addVideoToComment':
                        linkToolsForm.css('background-image', 'url(/Images/kiltr_v2/feed/commentVideoAttachmentBackg.gif)');
                        linkUrl.val("Type or paste your Vimeo, YouTube or Livestream URL");
                        break;

                    default:
                        linkToolsForm.css('background-image', 'url(/Images/kiltr_v2/feed/commentLinkAttachmentBackgr.gif)');
                }

                linkToolsDiv.slideDown(0, function () {
                    linkToolsForm.show();
                });
            });
        } else {

            $('.commentUploadTools').hide();
            commentAreaBottom.css('width', '532px');
            linkToolsDiv = commentAreaBottom.find('.linkToolsDiv');
            linkToolsForm = linkToolsDiv.find('#linkFormTools');
            var linkUrl = linkToolsForm.find('.textboxNew');
            linkToolsForm.hide();
            linkToolsDiv.find('#linkPreview').hide();
            linkToolsDiv.hide();
            linkToolsForm.find('.onTop').html(GetAttachmentPrompt(icon));
            switch (selectedTypeClass) {

                case 'addLinkToComment':

                    linkToolsForm.css('background-image', 'url(/Images/kiltr_v2/feed/commentLinkAttachmentBackgr.gif)');
                    linkUrl.val("Type or paste a link");
                    $('#commentVideoTools,.videoPreview').hide();
                    $(".commentAudioTools").hide();
                    if ($(".linkToolsDiv #linkPreviewTitle").html() != "") {
                        $('.linkToolsDiv').show();
                        $('.linkToolsDiv #linkPreview').show();
                        //linkToolsForm.hide();
                        $("#linkToolsClose").show();
                        $("#commentVideoTools #videoToolsClose, .commentAudioTools #audioToolsClose").hide();
                    } else {
                        //linkToolsForm.show();
                        $('#linkPreview').hide();
                        $("#commentVideoTools #videoToolsClose, #linkToolsClose, .commentAudioTools #audioToolsClose").hide();
                        linkToolsDiv.slideDown(0, function () {
                            linkToolsForm.fadeIn(1000);
                        });
                    }
                    break;

                case 'addAudioToComment':
                    linkToolsForm.css('background-image', 'url(/Images/kiltr_v2/feed/commentAudioAttachmentBackg.gif)');
                    linkUrl.val("Type or Paste your SoundCloud or MixCloud URL");
                    $('#linkPreview').hide();
                    $('#commentVideoTools,.videoPreview').hide();
                    if ($("#audioPreview object").length > 0) {
                        $('.commentAudioTools').show();
                        //linkToolsForm.hide();
                        $("#commentLinkTools").hide();
                        $(".commentAudioTools #audioToolsClose").show();
                        $("#linkToolsClose, #commentVideoTools #videoToolsClose").hide();
                    } else {
                        //linkToolsForm.show();
                        $('.commentAudioTools').hide();
                        $("#commentVideoTools #videoToolsClose, #linkToolsClose, .commentAudioTools #audioToolsClose").hide();
                        linkToolsDiv.slideDown(0, function () {
                            linkToolsForm.fadeIn(1000);
                        });
                    }
                    break;

                case 'addVideoToComment':
                    linkToolsForm.css('background-image', 'url(/Images/kiltr_v2/feed/commentVideoAttachmentBackg.gif)');
                    linkUrl.val("Type or paste your Vimeo, YouTube or Livestream URL");
                    $('#linkPreview').hide();
                    $(".commentAudioTools").hide();
                    if ($(".videoPreview object").length > 0) {
                        $('#commentVideoTools,.videoPreview').show();
                        //linkToolsForm.hide();
                        $("#commentLinkTools").hide();
                        $("#commentVideoTools #videoToolsClose").show();
                        $(".commentAudioTools #audioToolsClose").hide();
                    } else {
                        //linkToolsForm.show();
                        $('#commentVideoTools,.videoPreview').hide();
                        $("#commentVideoTools #videoToolsClose, #linkToolsClose, .commentAudioTools #audioToolsClose").hide();
                        linkToolsDiv.slideDown(0, function () {
                            linkToolsForm.fadeIn(1000);
                        });
                    }
                    break;

                default:
                    linkToolsForm.css('background-image', 'url(/Images/kiltr_v2/feed/commentLinkAttachmentBackgr.gif)');
            }
        }
    });


    $('#videoToolsClose').live('click', CloseAndRemoveVideo);

    $('#audioToolsClose').live('click', CloseAndRemoveAudio);

    /* pick this up */
    $('#linkToolsClose').live('click', CloseAndRemoveLinks);

    function CloseAndRemoveLinks() {
        $(this).parent().hide();
        $("#thumbnailController").hide();
        $("#linkPreviewImageWindow").hide();
        $('#linkUrl').val('');

        $('#linkPreviewImage, #linkPreviewTitle, #linkPreviewIntro, #linkPreviewUrl').html('');
        $('#hiddenLinkUrl, #hiddenLinkTitle, #hiddenLinkIntro, #hiddenLinkThumbnail').val('');
        //        $('#totalImages').html('0');
        //        $('#currentImage').html('1');
        $("#linkPreviewImage").css("margin-left", "0px");
        $("#linkTools, #linkFormTools").show();
        $("#linkPreview").hide();
        $(this).hide();
    }

    function CloseAndRemoveVideo() {
        $(this).parent().hide();
        $('#linkUrl').val('');
        $("#videoUrl").val("");
        $('.videoPreview').html('');
        $("#linkTools, #linkFormTools").show();
        $("#linkPreview").hide();
        $(this).hide();
        resetAttachmentIconsToDefault();
    }

    function resetAttachmentIconsToDefault() {
        $('.addImageToComment,.addVideoToComment,.addAudioToComment,.addLinkToComment').css('background-position', '0px -60px')
    }

    function CloseAndRemoveAudio() {
        $(this).parent().hide();
        $('#linkUrl').val('');
        $("#udioUrl").val("");
        $('.commentAudioTools #audioPreview').html('');
        $("#linkTools, #linkFormTools").show();
        $("#linkPreview").hide();
        $(this).hide();
        resetAttachmentIconsToDefault();
    }

    function CloseAndRemoveAll() {
        CloseAndRemoveAudio();
        CloseAndRemoveVideo();
        CloseAndRemoveLinks();
    }

    //    $('#addAudioToPost').live('click', function () {
    //        $('#ajax-audio-loader').show();
    //        $.post("/Post/ParseAudioUrl", {
    //            audioUrl: $('#audioUrl').val()
    //        }, function (response) {
    //            $('#audioFormTools').hide();
    //            $('#audioPreview').html(response);
    //            $('#ajax-audio-loader').hide();
    //        });
    //        return false;
    //    });

    //    $('.insertAudioIntoComment').live('click', function () {

    //        var parent = $(this).parent().parent();
    //        var master = parent.parent();
    //        var textbox = parent.find('.textbox');
    //        var ajaxLoader = parent.find('.ajax-video-loader');
    //        var audioPreview = master.find('#audioPreview');
    //        ajaxLoader.show();
    //        $('#ajax-audio-loader').show();

    //        $.post("/Post/ParseAudioUrl", {
    //            audioUrl: textbox.val()
    //        }, function (response) {
    //            $('#audioFormTools').hide();
    //            audioPreview.html(response);
    //            $('#ajax-audio-loader').hide();
    //            parent.hide();
    //        });
    //        return false;
    //    });


    $('#addLinkToPost').live('click', AddAttachment);

    function AddAttachment() {
        $(this).hide();
        var textbox = $('#linkUrl');
        if ($.trim(textbox.val()) == '') return false;
        $(".closeButton").show();
        $('#ajax-loader').show();
        $.post("/Post/ParseAnyUrl", {
            url: textbox.val()
        }, function (response) {
            $('#ajax-loader').hide();
            $('#linkFormTools').hide();
            if (typeof response.Title !== 'undefined') {
                fillLinkAttachment(response);
                $("#linkToolsClose").show();
                $("#addLink").css("background-position", ""); //changed from 0 0
                $("#addAudio").css("background-position", "0 -60px");
                $("#addVideo").css("background-position", "0 -60px");
            } else if (response.match(/^\s*<object height.+ class=".+CloudPlayer">/)) {
                $('#linkTools').hide();
                $('#audioPreview').html(response);
                $('#audioUrl').val(textbox.val());
                $("#audioToolsClose").show();
                $('#audioTools').slideDown(0, function () {
                    $('#audioPreview').fadeIn(1000);
                });
                $("#addLink").css("background-position", "0 -60px");
                $("#addAudio").css("background-position", ""); // changed
                $("#addVideo").css("background-position", "0 -60px");
            } else {
                $('#linkTools').hide();
                $('#videoPreview').html(response);
                $('#videoUrl').val(textbox.val());
                $("#videoToolsClose").show();
                $('#videoTools').slideDown(0, function () {
                    $('#videoPreview').fadeIn(1000);
                });
                $("#addLink").css("background-position", "0 -60px");
                $("#addAudio").css("background-position", "0 -60px");
                $("#addVideo").css("background-position", ""); //changed
            }
            $("#addLinkToPost").show();
            $("#linkUrl").val("");
        });


        return false;
    }

    $('.insertLinkIntoPost').live('click', function () {

        var parent = $(this).parent().parent();
        var linkTools = parent.parent();
        var master = linkTools.parent().parent();
        var textbox = parent.find('.textboxNew');
        var ajaxLoader = parent.find('.ajax-link-loader');
        var linkPreview = parent.next('div');
        var videoPreview = linkTools.parent().find('.videoPreview');
        var videoTools = videoPreview.parent();
        var audioPreview = linkTools.parent().find('#audioPreview');
        var audioTools = audioPreview.parent();

        if ($.trim(textbox.val()) == '') return false;

        ajaxLoader.show();
        idParts = master.attr('id').split('-');

        $.post("/Post/ParseAnyUrl", {
            url: textbox.val()
        }, function (response) {
            ajaxLoader.hide();
            parent.hide();
            if (typeof response.Title !== 'undefined') {
                fillCommentAttachment(response, linkPreview, idParts[1]);
            } else if (response.match(/^\s*<object height.+ class=".+CloudPlayer">/)) {
                linkTools.hide();
                audioPreview.html(response);
                $('#audioUrl-' + idParts[1]).val(textbox.val());
                $(audioTools).slideDown(0, function () {
                    $(audioPreview).fadeIn(1000);
                });
            } else {
                linkTools.hide();
                videoPreview.html(response);
                $('#videoUrl-' + idParts[1]).val(textbox.val());
                $(videoTools).slideDown(0, function () {
                    $(videoPreview).fadeIn(1000);
                });
            }
        });

        return false;
    });

    $('.replyNonFocused').live('focus', function () {

        pauseNetworkActivityFeed();
        var areaHeight = $(this).height();
        //$('.replySimulatedContainer').css('height', '88px');
        $(this).parent().css('height', '88px');
        $(this).next('.closeReplyPost').show();

        if (areaHeight != 50) {
            //$(this).css('height','70px');
            $(this).animate({
                height: '50px',
                easing: 'linear'
            }, 0, function () {
                // Animation complete.
            });
        }

        $(this).css('color', '#000');
        $(this).css('width', '410px'); //445 then 324 shortly before 310


        $(this).parent().css('margin-left', '0px');
        $(this).find('.icons').css('margin', '5px 5px 0px 0px');
        if ($(this).html() == 'reply to this post..') {
            $(this).html('');
        }

        var inputParent = $(this).parent().parent();
        var masterParent = inputParent.parent();
        var imageDiv = inputParent.prev();

        var actionDiv = masterParent.find('.inlinePostToolbar');
        var postReplyTools = masterParent.find('.postReplyTools');
        //$('.postReplyTools').show();
        $(this).parent().parent().parent().siblings(".postReplyTools").show();
        imageDiv.show();
        actionDiv.show();

    });

    $('*').live('click', function () {
        $('#lastClass').html($(this).attr('class'));
        $('#lastId').html($(this).attr('id'));

    });

    $('.replyIcon').live('click', function () {
        bubbleUp($(this), 'feedItem');
    });

    $('.profileCard').live('mouseover', function () {
        var actionBar = $(this).find('.cardActionBar,.cardActionBarReduced');
        actionBar.show();
        var closeButton = actionBar.next('div');
        closeButton.show();

    });

    $('.profileCard').live('mouseleave', function () {
        var actionBar = $(this).find('.cardActionBar,.cardActionBarReduced');
        actionBar.hide();
        var closeButton = actionBar.next('div');
        closeButton.hide();
    });

    $('.main-feed-item-container, .simpleItem, .profileCardSmall').live('mouseenter', function () {

        if (!$('#emptyModalDialogue').is(':visible')) {
            //$(this).css('background', '#F1F1F1');
            $(this).find('.cardActionBarWide, .cardActionBarReduced').first().show();
        }
    });

    $('.main-feed-item-container, .simpleItem, .profileCardSmall').live('mouseleave', function () {
        //$(this).css('background', '#FFFFFF');
        $(this).find('.cardActionBarWide, .cardActionBarReduced').first().hide();
    });

    $('.feedItemReply, .feedItemReplyAlt').live('mouseenter', function () {
        var isVisible = $('.inlineCommentEditor').is(':visible');
        if (isVisible == false) {

            var postText = $(this).find('p');
            var containerHeight = (postText.height() + 10);
            $(this).find('.postOverlay').height(containerHeight);
            $(this).find('.postOverlay').show();
            $(this).find('.postOverlayOverlay').height(containerHeight);
            $(this).find('.postOverlayOverlay').show();
            $(this).find('.postOverlayOverlay > .cardActionBarWide, .cardActionBarReduced').show();
        } else {
            /*$(this).find('.cardActionBarWide, .cardActionBarReduced').show();*/
        }
    });

    $('.replyIconPublic').live('click', function () {

        var reposition = (($(window).scrollTop()) + 85);
        var joinGroupLinkParts = $('.joinGroupLink > a').attr('href').split('/');
        var idParts = $(this).attr('id').split("-");

        $('#additionalAction').html(idParts[1]);
        $('#modalPrompt').css('margin-top', reposition + 'px');
        $('#modalPrompt').css('margin-left', '35%');
        $('#promptMessage').html('To post you must be a member of this group. Join now?');
        $('.intendedAction').attr('id', 'joinGroup');
        $('.intendedAction').html(joinGroupLinkParts[3]);   // pretty sure this is wrong - there only are 3 parts and indices start at zero usually
        $('#intendedActionSuccess').html('Thank you, you have successfully joined this group');

        $('.promptTitle').html('Join Group');
        $('#modalPrompt').show();
        $(".closeModalDialog").show(); //Force close cross to show

        return false;
    });

    $('.feedItemReply, .feedItemReplyAlt').live('mouseleave', function () {
        $(this).find('.postOverlay').hide();
        $(this).find('.postOverlayOverlay').hide();
    });

    //    $('#deleteWhoViewedMyProfile.cardClose').live('click', function () {

    //        var currentPageDiv = $('#whoHasViewedMyProfileCurrentPage'); //current page index
    //        var pageSizeDiv = currentPageDiv.next('#whoHasViewedMyProfilePageSize'); //page size

    //        var currentPage = parseInt(currentPageDiv.html());
    //        var pageSize = parseInt(pageSizeDiv.html());
    //        var numberToDisplay = (currentPage * pageSize);

    //        var inputParent = $(this).parent();
    //        var id = inputParent.attr('id').split('-')[1];

    //        inputParent.html('<img src="/Images/ported/common/ajax-loader-transparent.gif" class="paddedAjaxLoader">');
    //        $.post("/MyKiltr/DeleteWhoViewedMyProfile", {
    //            whoViewedMyProfileId: id,
    //            numberToReturn: numberToDisplay
    //        }, function (response) {
    //            $('#whoHasViewedYourProfileContainer').html(response);
    //            $('#whoHasViewedMyProfileCount').html($('#whoHaveViewedMyProfileTotalCount').val());
    //        });
    //        return false;
    //    });

    $('.cardCloseGroup').live('click', function () {

        var currentPageDiv = $('#groupRecommendationsCurrentPage'); //current page index
        var pageSizeDiv = currentPageDiv.next('#groupRecommendationsPageSize'); //page size

        var currentPage = parseInt(currentPageDiv.html());
        var pageSize = 4;
        var numberToDisplay = (currentPage * pageSize);

        var inputParent = $(this).parent();
        var id = inputParent.attr('id').split('-')[1];


        inputParent.html('<img src="/Images/ported/common/ajax-loader-transparent.gif" class="paddedAjaxLoader">');
        $.post("/MyKiltr/AddGroupExclusion", {
            groupId: id,
            pageSize: pageSize
        }, function (response) {
            $('#groupRecommendationsContainer').html(response);

            $('#totalGroupRecommendations').html($('#groupRecommendationsTotalCount').val());

            if ($('#groupRecommendationsTotalCount').val() <= pageSize) {
                $('#seeMoreGroupRecommendations').hide();
            }
        });
        return false;
    });

    $('.cardCloseUser').live('click', function () {

        var currentPageDiv = $('#peopleRecommendationsCurrentPage'); //current page index
        var pageSizeDiv = currentPageDiv.next('#peopleRecommendationsPageSize'); //page size

        var currentPage = parseInt(currentPageDiv.html());
        var pageSize = 4;
        var numberToDisplay = (currentPage * pageSize);

        var inputParent = $(this).parent();
        var id = inputParent.attr('id').split('-')[1];

        inputParent.html('<img src="/Images/ported/common/ajax-loader-transparent.gif" class="paddedAjaxLoader">');
        $.post("/MyKiltr/AddUserExclusion", {
            userId: id,
            pageSize: pageSize
        }, function (response) {
            $('#peopleRecommendationsContainer').html(response);

            $('#totalPeopleRecommendations').html($('#peopleRecommendationsTotalCount').val());

            if ($('#peopleRecommendationsTotalCount').val() <= pageSize) {
                $('#seeMorePeopleRecommendations').hide();
            }
        });
        return false;
    });

    $('.cardClose').live('click', function () {
        var inputParent = $(this).parent();
        var idParts = inputParent.attr('id').split("-");
        var userId = idParts[1];
        inputParent.html('<img src="/Images/ported/common/ajax-loader-transparent.gif" class="paddedAjaxLoader">');
        $.post("/People/RemoveContact", {
            id: userId
        }, function (response) {
            inputParent.fadeOut('500');
            notifyUser(response);
        });
        return false;
    });

    $('.cardCloseAlt').live('click', function () {

        var inputParent = $(this).parent();
        var idParts = inputParent.attr('id').split("-");
        var connectionStatus = inputParent.find('.iconConnectionStatus');

        if (connectionStatus.attr('id') == 'contactIndicator' || connectionStatus.attr('id') == 'inviteIndicator') {
            $('#promptMessage').html('Are you sure you wish to delete this contact?');
            $('.promptTitle').html('Delete contact');
            $('.intendedAction').html(idParts[1]);
            $('.intendedAction').attr('id', 'deleteContact');
            $('#intendedActionSuccess').html('Thank you, your contact has been deleted');

        } else if (connectionStatus.attr('id') == 'connectionIndicator') {
            $('#promptMessage').html('Are you sure you wish to delete this connection?');
            $('.promptTitle').html('Delete conections');
            $('.intendedAction').html(idParts[1]);
            $('.intendedAction').attr('id', 'deleteConnection');
            $('#intendedActionSuccess').html('Thank you, your connection has been deleted');
        }
        else {
            //added to handle standard profile card deletes
            $('#promptMessage').html('Are you sure you wish to delete this connection?');
            $('.promptTitle').html('Delete conections');
            $('.intendedAction').html(idParts[1]);
            $('.intendedAction').attr('id', 'deleteConnection');
            $('#intendedActionSuccess').html('Thank you, your connection has been deleted');
        }

        $('#callback').html('$(\'#' + inputParent.attr('id') + '\').remove();');

        $('#modalPrompt').show();
        $(".closeModalDialog").show(); //Force close cross to show
        var reposition = (($(window).scrollTop()) + 45);
        $('#modalPrompt').css('margin-top', reposition + 'px');


    });

    $('.iconMessage, .sendContactMessage').live('click', function () {  // TODO: Refactor with #newMessage,.newMessage
        HideMiniProfile();
        $('.hovercard').hide();
        CloseGallery();
        styleMessageWindow();
        var reposition = (($(window).scrollTop()) + 45);

        $('#message').css('margin-top', reposition + 'px');
        $('#message').show();
        $("#message").draggable({ handle: '.modalHeader' });

        var classParts = $(this).attr('class').split(" ");
        var idParts = $(this).attr('id').split("-");

        $.post("/Ajax/GetDelimitedUserInfo", {  // TODO: Remove this? - shouldn't be needed in most situations
            action: classParts[1],
            userid: idParts[1]

        }, function (response) {
            //as this is the first click assume its a new message and the to fields should be emptied.
            $('.inputStorage').val('');
            $('.recipient').remove();

            var responseParts = response.split("-");
            $('.suggestableHidden').before('<div class="recipient" id="item-' + responseParts[0] + '"><div class="recipientName">' + responseParts[1] + '</div><div class="recipientCloseContainer"><img src="/Images/ported/messageCenter/recipientClose.gif" class="itemClose"></div></div>');
            var currentRecipients = $('.inputStorage').val();
            $('.inputStorage').val(currentRecipients + responseParts[0]);

        });
        return false;
    });

    $('.iconAction').live('click', function () {

        var classParts = $(this).attr('class').split(" ");
        var idParts = $(this).attr('id').split("-");

        if (idParts.length == 1) { return; }

        if ($(this).parent().attr('class') == 'cardActionBarWide' || $(this).parent().attr('class') == 'cardActionBar' || $(this).parent().attr('class') == 'decisionBar' || $(this).parent().attr('class') == 'cardActionBarReduced') {
            var parent = $(this).parent();
            var gestureBar = parent.prev('div');
            var displayMessage = true;
            var speechBubble = $(this).next('div');
            /* gestures!! */

            switch (idParts[1]) {

                case 'manage':
                    if (idParts[0] == 'group') {
                        document.location.replace('/Group/Edit/' + idParts[2]);
                    } else if (idParts[0] == 'event') {
                        document.location.replace('/Event/Edit/' + idParts[2]);
                    } else if (idParts[0] == 'organisation') {
                        document.location.replace('/Organisation/Edit/' + idParts[2]);
                    } else if (idParts[0] == 'products') {
                        document.location.replace('/Products/Edit/' + idParts[2]);
                    }

                    break;
                case 'join':
                    if (idParts[0] == 'group') {
                        document.location.replace('/Group/JoinGroup/' + idParts[2]);
                        return;
                    }
                    break;
                case 'attending':
                    //TODO: Refactor into single method
                    $.ajax({
                        url: "/Event/Attend/" + idParts[2],
                        success: function (data) {
                            if (data == "1") {
                                notifyUser("You are now attending this event");
                            } else {
                                notifyUser("An error occurred. Please try again");
                            }
                        }
                    });
                    break;
                case 'notattending':
                    $.ajax({
                        url: "/Event/Decline/" + idParts[2],
                        success: function (data) {
                            if (data == "1") {
                                notifyUser("Your feedback has been registered");
                            } else {
                                notifyUser("An error occurred. Please try again");
                            }
                        }
                    });
                    break;
                case 'maybe':
                    $.ajax({
                        url: "/Event/Maybe/" + idParts[2],
                        success: function (data) {
                            if (data == "1") {
                                notifyUser("Your feedback has been registered");
                            } else {
                                notifyUser("An error occurred. Please try again");
                            }
                        }
                    });
                    break;
                case 'cancel':
                    speechBubble = $(this).find('.miniSpeechIcon');
                    speechBubble.html('Delete');

                    var idParts = $(this).attr('id').split('-');
                    $('.inlineEditor').remove();
                    $('#postBody-' + idParts[2]).show();

                    speechBubble2 = $('#post-save-' + idParts[2]).find('.miniSpeechIcon');
                    speechBubble2.html('Edit');

                    $(this).removeClass('iconCancel').addClass('iconDelete');
                    $(this).removeClass('cancelEdit').addClass('deletePost');
                    $(this).attr('id', 'post-delete-' + idParts[2]);

                    $('#post-save-' + idParts[2]).removeClass('iconSave').addClass('iconEdit');
                    $('#post-save-' + idParts[2]).removeClass('savePost').addClass('editPost');
                    $('#post-save-' + idParts[2]).attr('id', 'post-edit-' + idParts[2]);
                    return;

                case 'commentCancel':
                    var container = $(this).parent();
                    var idParts = $(this).attr('id').split('-');
                    $('.inlineCommentEditor').remove();
                    $('#commentBody-' + idParts[2]).show();
                    container.hide();
                    break;

                case 'save':

                    speechBubble = $(this).find('.miniSpeechIcon');
                    speechBubble.html('Edit');

                    var idParts = $(this).attr('id').split('-');
                    var editedText = $('.inlineEditor').val();
                    var formattedText = editedText.replace(/\n/gi, "<br />");

                    $(this).removeClass('iconSave').addClass('iconEdit');
                    $(this).removeClass('savePost').addClass('editPost');
                    $(this).attr('id', 'post-edit-' + idParts[2]);

                    speechBubble2 = $('#post-cancel-' + idParts[2]).find('.miniSpeechIcon');
                    speechBubble2.html('Delete');

                    $('#post-cancel-' + idParts[2]).removeClass('iconCancel').addClass('iconDelete');
                    $('#post-cancel-' + idParts[2]).removeClass('cancelEdit').addClass('deletePost');
                    $('#post-cancel-' + idParts[2]).attr('id', 'deletePost-' + idParts[2]);

                    $.post("/Post/Update", {
                        postId: idParts[2],
                        revisedText: editedText
                    }, function (response) {

                        $('#postBody-' + idParts[2]).html(formattedText);
                        $('.inlineEditor').remove();
                        $('#postBody-' + idParts[2]).show();
                        startNetworkActivityFeed();
                        updateNetworkActivityFeed();

                        notifyUser(response + 'Thank you, your post has now been edited.');
                    });

                    return;

                case 'commentSave':

                    speechBubble = $(this).find('.miniSpeechIcon');
                    speechBubble.html('Edit');

                    var idParts = $(this).attr('id').split('-');
                    var editedText = $('.inlineCommentEditor').val();
                    var formattedText = editedText.replace(/\n/gi, "<br />");
                    var container = $(this).parent();

                    $.post("/Post/UpdateComment", {
                        commentId: idParts[2],
                        revisedText: editedText
                    }, function (response) {
                        $('#commentBody-' + idParts[2]).html(response);
                        $('.inlineCommentEditor').remove();
                        $('#commentBody-' + idParts[2]).show();
                        startNetworkActivityFeed();
                        //updateNetworkActivityFeed();
                        notifyUser('Thank you, your comment has now been edited.');
                        container.hide();
                    });
                    return;

                case 'edit':

                    speechBubble = $(this).find('.miniSpeechIcon');
                    speechBubble.html('Save');

                    pauseNetworkActivityFeed();
                    var idParts = $(this).attr('id').split('-');
                    var currentContent = $('#postBody-' + idParts[2]).html();
                    var formattedContent = $('<div/>').html(currentContent.replace(/<br>/gi, "\n")).text();

                    $(this).removeClass('iconEdit').addClass('iconSave');
                    speechBubble2 = $('#post-delete-' + idParts[2]).find('.miniSpeechIcon');
                    speechBubble2.html('Cancel');

                    $('#post-delete-' + idParts[2]).removeClass('iconDelete').addClass('iconCancel');
                    $('#post-delete-' + idParts[2]).removeClass('deletePost').addClass('cancelEdit');
                    $('#post-delete-' + idParts[2]).attr('id', 'post-cancel-' + idParts[2]);

                    $(this).attr('id', 'post-save-' + idParts[2]);
                    $(this).removeClass('editPost').addClass('savePost');

                    $('#postBody-' + idParts[2]).hide();
                    $('#postBody-' + idParts[2]).after('<textarea class="inlineEditor" id="postEditCopy-' + idParts[2] + '">' + jQuery.trim(formattedContent) + '</textarea>');

                    return;

                case 'commentEdit':

                    var prevDiv = $(this).parent().parent().prev('div').find('.cardActionBarWide');
                    prevDiv.show();
                    $(this).parent().hide();
                    $('.postOverlay').hide();
                    speechBubble = $(this).find('.miniSpeechIcon');
                    /*speechBubble.html('Save');*/

                    pauseNetworkActivityFeed();
                    var idParts = $(this).attr('id').split('-');
                    var currentContent = $('#commentBody-' + idParts[2]).html();
                    var formattedContent = $('<div/>').html(currentContent.replace(/<br>/gi, "\n")).text();

                    $('#commentBody-' + idParts[2]).hide();
                    $('#commentBody-' + idParts[2]).after('<textarea class="inlineCommentEditor" id="commentEditCopy-' + idParts[2] + '">' + jQuery.trim(formattedContent) + '</textarea>');
                    $('#commentBody-' + idParts[2]).next().next().show();

                    return;

                case 'delete':
                    $('#intendedActionSuccess').html('Thank you, your post has now been deleted.');
                    var idParts = $(this).attr('id').split('-');
                    $('#callback').html('$("#' + $(this).parents('.feedItem').attr('id') + '").parent().remove(); $(".newPosts").html(parseInt($(".newPosts").html())-1);');
                    $('#modalPrompt').show();
                    $(".closeModalDialog").show(); //Force close cross to show.
                    var reposition = (($(window).scrollTop()) + 45);
                    $('#modalPrompt').css('margin-top', reposition + 'px');
                    $("#modalPrompt").draggable({ handle: '.modalHeader' });
                    $('#promptMessage').html('Are you sure you wish to delete this post?');
                    $('.promptTitle').html('Delete post');
                    $('.intendedAction').html(idParts[2]);
                    $('.intendedAction').attr('id', 'deletePost');

                    return;

                case 'commentDelete':
                    $('#intendedActionSuccess').html('Thank you, your comment has now been deleted.');
                    var idParts = $(this).attr('id').split('-');
                    $('#callback').html('$("#commentBody-' + idParts[2] + '").parents(".feedItemReply").remove();');
                    $('#modalPrompt').show();
                    $(".closeModalDialog").show(); //Force close cross to show.
                    var reposition = (($(window).scrollTop()) + 45);
                    $('#modalPrompt').css('margin-top', reposition + 'px');
                    $('#promptMessage').html('Are you sure you wish to delete this comment?');
                    $('.promptTitle').html('Delete comment');
                    $('.intendedAction').html(idParts[2]);
                    $('.intendedAction').attr('id', 'deleteComment');

                    break;

                case 'share':

                    /*  		
                    if (idParts[0] == 'group') {
                    $.post("/Ajax/CreateGroupRecommendationNotification", {
                    groupId: idParts[2]
                    }, function (response) {
                    notifyUser('The group has been posted to your activity feed.');
                    });
                    } else if (idParts[0] == 'post') {
                    $.post("/Ajax/CreatePostRecommendationNotification", {
                    postId: idParts[2]
                    }, function (response) {
                    notifyUser('Thanks, you have now shared this post with your connections.');
                    weePipe();
                    });
                    } else if (idParts[0] == 'event') {
                    $.post("/Ajax/ShareEvent", {
                    eventId: idParts[2]
                    }, function (response) {
                    notifyUser('The event has been shared with your connections.');
                    weePipe();
                    });
                    }
                    */
                    return false;

                case 'like':
                    var target = gestureBar.find('.gestureLike, .likeCount');
                    if (incrementNumber(target)) {
                        //if (!target.hasClass('whoGestured')) target.addClass('whoGestured').addClass('underline');    // need to have id in it already for this to work
                    }
                    $(this).remove();
                    notifyUser('Thanks you have given this ' + idParts[0] + ' the thumbs up!');
                    displayMessage = false;
                    break;

                case 'dislike':
                    var target = gestureBar.find('.gestureDislike, .dislikeCount');
                    if (incrementNumber(target)) {
                        //if (!target.hasClass('whoGestured')) target.addClass('whoGestured').addClass('underline');    // need to have id in it already fo rthis to work
                    }
                    $(this).remove();
                    notifyUser('Thanks you have given this ' + idParts[0] + ' the thumbs down!');
                    displayMessage = false;
                    break;

                case 'accept':
                    var parentDiv = $(this).parent();
                    var surroundDiv = parentDiv.parent();
                    var surroundDiv = surroundDiv.parent();
                    if (surroundDiv.attr("class") == 'messageSummaryBody')
                        surroundDiv = surroundDiv.parent();

                    var currentQtyInvites = parseInt($('.rightNavInviteCount').html());
                    $('.rightNavInviteCount').html(currentQtyInvites - 1);
                    if (currentQtyInvites == 1) {
                        $("#accordionSmall").accordion("option", "active", -1);
                        surroundDiv.after('<p class=\'widgetEmptyMessage\'>You have no invitations.</p>');
                    }
                    if (surroundDiv.attr("class") == 'miniInvite' || surroundDiv.attr("class") == 'messageSummary') {
                        surroundDiv.remove();
                    }
                    notifyUser('Thanks you have accepted this invitation!');
                    break;

                case 'decline':
                    var parentDiv = $(this).parent();   // decisionBar
                    var surroundDiv = parentDiv.parent(); // miniInviteRight
                    var surroundDiv = surroundDiv.parent(); // miniInvite
                    var currentQtyInvites = parseInt($('.rightNavInviteCount').html());
                    $('.rightNavInviteCount').html(currentQtyInvites - 1);
                    if (currentQtyInvites == 1) {
                        $("#accordionSmall").accordion("option", "active", -1);
                        surroundDiv.after('<p class=\'widgetEmptyMessage\'>You have no invitations.</p>');
                    }
                    if (surroundDiv.attr("class") == 'miniInvite') {
                        surroundDiv.remove();
                    } else if (surroundDiv.attr("class") == 'messageSummaryBody') {
                        parentDiv = surroundDiv.parent().parent('li').parent('ul');
                        if (parentDiv.siblings('ul').size() == 0) {
                            parentDiv.replaceWith('<p class="emptySection">You currently have no invites.</p>');
                        } else {
                            parentDiv.remove();
                        }
                    }

                    notifyUser('Thanks you have declined this invitation!');
                    break;

                case 'report':

                    var reposition = (($(window).scrollTop()) + 45);
                    $('#message').css('margin-top', reposition + 'px');
                    $('#message').show();
                    $("#message").draggable({ handle: '.modalHeader' });
                    var actionIdParts = $(this).attr('id').split('-');
                    var replacementText = '';
                    var currentStorageValue = $('#inputStorage').val();
                    var senderId = $('.messageFrom').attr('id');
                    var fromName = $('#fromName').html();
                    $('.recipient').remove();
                    $('.suggestableHidden').before('<div class="recipient" id="recipient-10005"><div class="recipientName">report@kiltr.com</div><div class="recipientCloseContainer"><img src="/Images/ported/messageCenter/recipientClose.gif" class="recipientClose"></div></div>');
                    $('#messageSubject').val('Report: ' + idParts[0] + ' ' + idParts[2]);
                    $('#messageBody').val('Please tell us the reasons why you would like to report this to KILTR and we\'ll look into it. Thank you for your feedback and helping us to keep KILTR a trusted and safe environment.\n\nThe KILTR team\n' + replacementText);
                    $('.inputStorage').val(10005);
                    styleReportWindow();

                    return false;

                case 'profile':
                    window.location = '/' + idParts[2];
                    return;
                    //break;

                    var target = gestureBar.find('.gestureLike');
                    targetValue = target.html();
                    targetValue = targetValue.replace('(', '');
                    targetValue = targetValue.replace(')', '');
                    newValue = parseInt(targetValue) + 1;
                    target.html('(' + newValue + ')');
                    $(this).remove();
                    break;

            }
        }

        $.post("/Ajax/ActionHandler", {
            entity: idParts[0],
            action: idParts[1],
            id: idParts[2]
        }, function (response) {
            //console.log('before');
            if (response != '0') {
                notifyUser(response);
            }
        });

        var parentDiv = $(this).parent();
        var surroundDiv = parentDiv.parent();
        if (surroundDiv.attr('id') == 'invite') {
            //window.location = '/MyKiltr/Invites';
            surroundDiv.find('.decisionBar').hide();
        }
        else if (parentDiv.attr('class') == 'decisionBar') {
            parentDiv.hide();
        }

        return false;
    });

    $('.kiltrShare').live('click', function () {
        var idParts = $(this).attr('id').split('-');

        if (idParts[0] == 'group') {
            $.post("/Ajax/CreateGroupRecommendationNotification", {
                groupId: idParts[2]
            }, function (response) {
                notifyUser('The group has been posted to your activity feed.');
            });
        } else if (idParts[0] == 'post') {
            $.post("/Ajax/CreatePostRecommendationNotification", {
                postId: idParts[2]
            }, function (response) {
                notifyUser('Thanks, you have now shared this post with your connections.');
                weePipe();
            });
        } else if (idParts[0] == 'event') {
            $.post("/Ajax/ShareEvent", {
                eventId: idParts[2]
            }, function (response) {
                notifyUser('The event has been shared with your connections.');
                weePipe();
            });
        }

        return false;

    });

    $('.cardTitle,.cardTitleSmall').live('mouseover', function () {
        /* hovercard positioning */

        var parentDiv = $(this).parent();
        var parentDiv2 = parentDiv.parent();
        var idParts = parentDiv2.attr('id').split('-');
        if (idParts[1] == null || isNaN(idParts[1])) return;

        var hoverCardHeight = $('.hovercard').height();
        var finalTopLocation = $(this).offset().top - hoverCardHeight;
        var finalPositionLeft = $(this).offset().left;

        $('.hovercard').show();
        $('.hovercard').css('z-index', '100000');
        $('.hovercard').css('top', finalTopLocation + 'px');
        $('.hovercard').css('left', finalPositionLeft + 'px');
        $('.hovercard').html('<img src="/Images/ported/ajax-loader-white.gif" class="hovercardAjaxLoader">');
        /* hovercard positioning stop*/

        $.post("/People/MiniProfile", {
            userId: idParts[1]
        }, function (response) {
            $('.hovercard').html(response);
            $(".hovercardFooter").click(ShowSharedConnections); //2nd of a 2-part hack for diaspora hovercards shared connections functionality
        });
        return false;
    });

    $('#linkedInTab').live('click', function () {
        resetImportTabs();
        $('.importInstructions').hide();
        $('#linkedInInstructions').show();
        $('#linkedInTabImage').attr('src', '/Images/ported/genericInterface/tabs/linkedInOn.gif');
        $('#linkedInTab').removeClass('networkTabOff').addClass('networkTabOn');
    });

    $('#gmailTab').live('click', function () {
        resetImportTabs();
        $('.importInstructions').hide();
        $('#gmailInstructions').show();
        $('#gmailTabImage').attr('src', '/Images/ported/genericInterface/tabs/gmailOn.gif');
        $('#gmailTab').removeClass('networkTabOff').addClass('networkTabOn');
    });

    $('#outlookTab').live('click', function () {
        resetImportTabs();
        $('.importInstructions').hide();
        $('#outlookInstructions').show();
        $('#outlookTabImage').attr('src', '/Images/ported/genericInterface/tabs/outlookOn.gif');
        $('#outlookTab').removeClass('networkTabOff').addClass('networkTabOn');
    });

    $('#outlookExpressTab').live('click', function () {
        resetImportTabs();
        $('.importInstructions').hide();
        $('#outlookExpressInstructions').show();
        $('#outlookExpressTabImage').attr('src', '/Images/ported/genericInterface/tabs/outlookExpressOn.gif');
        $('#outlookExpressTab').removeClass('networkTabOff').addClass('networkTabOn');
    });

    $('#macMailTab').live('click', function () {
        resetImportTabs();
        $('.importInstructions').hide();
        $('#macMailInstructions').show();
        $('#macMailTabImage').attr('src', '/Images/ported/genericInterface/tabs/macMailOn.gif');
        $('#macMailTab').removeClass('networkTabOff').addClass('networkTabOn');
    });

    $('#hotmailTab').live('click', function () {
        resetImportTabs();
        $('.importInstructions').hide();
        $('#hotmailInstructions').show();
        $('#hotmailTabImage').attr('src', '/Images/ported/genericInterface/tabs/hotmailOn.gif');
        $('#hotmailTab').removeClass('networkTabOff').addClass('networkTabOn');
    });

    $('#addIndividualAddresses').live('click', function () {
        $('#importOverview').hide();
        $('#individualInvites').show();
    });

    $('.widgetTabLargeOff.top').live('click', function () {
        $('.widgetTabLargeOn.top').removeClass('widgetTabLargeOn').addClass('widgetTabLargeOff');
        $(this).removeClass('widgetTabLargeOff').addClass('widgetTabLargeOn');
    });

    $('.widgetTabLargeOff.bottom').live('click', function () {
        $('.widgetTabLargeOn.bottom').removeClass('widgetTabLargeOn').addClass('widgetTabLargeOff');
        $(this).removeClass('widgetTabLargeOff').addClass('widgetTabLargeOn');
    });

    $('#viewImportOptions').live('click', function () {
        $('#individualInvites').hide();
        $('#importOverview').show();
    });

    //    $('.newlyRegistered').live('mouseover', function (e) {
    //        
    //        if (!$(this).data('init')) {
    //            $(this).data('init', true);

    //            $('.newlyRegistered').bind("hover", { speed: 500, delay: 500 }, function () {

    //                /* hide any feeling bubbles that are kickin about */
    //                $('.feelingBubble').hide();
    //                /* hovercard positioning traverses up the dom and matches different hooks for different areas*/
    //                var usernameFieldId = $(this).attr('id');
    //                var usernameFieldIdParts = usernameFieldId.split('-');
    //                if (usernameFieldIdParts[1] == null || isNaN(usernameFieldIdParts[1])) return;

    //                var hoverCardHeight = $('.hovercard').height() + 15;
    //                var finalTopLocation = $(this).offset().top - hoverCardHeight;
    //                var finalPositionLeft = $(this).offset().left - 200;

    //                $('.hovercard').css('background-image', 'url(/Images/ported/myKiltr/hovercardBackgroundLeft.png)');
    //                $('.hovercard').show();
    //                $('.hovercard').css('z-index', '100000');
    //                $('.hovercard').css('top', finalTopLocation + 'px');
    //                $('.hovercard').css('left', finalPositionLeft + 'px');
    //                $('.hovercard').html('<img src="/Images/ported//common/ajax-loader-transparent.gif" class="hovercardAjaxLoader">');
    //                $('.hovercard').css('height', '150px');

    //                /* hovercard positioning stop*/
    //                if ($('#hovercardFiring').html() == 0) {
    //                    $('#hovercardFiring').html(1);
    //                    $.post("/People/MiniProfile", {
    //                        userId: usernameFieldIdParts[1]
    //                    }, function (response) {
    //                        $('.hovercard').html(response);
    //                        $('#hovercardFiring').html(0);
    //                    });
    //                }
    //            });

    //            $(this).trigger(e);
    //        }
    //    });


    //    $('.username').live('mouseover', function () {

    //        var hovercardFired = parseInt($('#hovercardFired').html());

    //        /* needed for proper ajax hover intent */
    //        if (!$(this).data('init')) {
    //            $(this).data('init', true);
    //            $('.username').bind("hover", { speed: 500, delay: 300 }, function () {
    //                $('#hovercardFired').html(hovercardFired + 1);
    //                /* hide any feeling bubbles that are kickin about */
    //                $('.feelingBubble').hide();
    //                /* hovercard positioning traverses up the dom and matches different hooks for different areas*/


    //                var usernameFieldId = $(this).attr('id');

    //                var userId;

    //                if (usernameFieldId == "fromName") {
    //                    userId = $(".messageFrom").attr("id");
    //                } else {
    //                    var usernameFieldIdParts = usernameFieldId.split('-');
    //                    if (usernameFieldIdParts[1] == null || isNaN(usernameFieldIdParts[1])) return;
    //                    userId = usernameFieldIdParts[1];
    //                }

    //                var hoverCardHeight = $('.hovercard').height();
    //                var finalTopLocation = $(this).offset().top - hoverCardHeight;
    //                var finalPositionLeft = $(this).offset().left;
    //                $('.hovercard').css('background-image', 'url(/Images/ported/myKiltr/hovercardBackground.png)');
    //                $('.hovercard').show();
    //                $('.hovercard').css('z-index', '100000');
    //                $('.hovercard').css('top', finalTopLocation + 'px');
    //                $('.hovercard').css('left', finalPositionLeft + 'px');
    //                $('.hovercard').html('<img src="/Images/ported/ajax-loader-white.gif" class="hovercardAjaxLoader">');
    //                /* hovercard positioning stop*/

    //                if ($('#hovercardFiring').html() == 0) {
    //                    $('#hovercardFiring').html(1);
    //                    $.post("/People/MiniProfile", {
    //                        userId: userId
    //                    }, function (response) {
    //                        if ($('.hovercard').html() != response) {
    //                            $('.hovercard').html(response);
    //                            $('#hovercardFiring').html(0);
    //                        }
    //                    });
    //                }

    //                return false;
    //            });

    //            if (hovercardFired == 0) {
    //                $(this).trigger('mouseover');
    //            }
    //        }
    //    });


    //    $('.groupName').live('mouseover', function () {

    //        var hovercardFired = parseInt($('#hovercardFired').html());

    //        if (!$(this).data('init')) {
    //            $(this).data('init', true);
    //            $('.groupName').bind("hover", { speed: 200, delay: 300 }, function () {
    //                $('#hovercardFired').html(hovercardFired + 1);
    //                /* hovercard positioning traverses up the dom and matches different hooks for different areas*/
    //                var groupFieldId = $(this).attr('id');
    //                var groupFieldIdParts = groupFieldId.split('-');

    //                var hoverCardHeight = $('.hovercard').height();
    //                var finalTopLocation = $(this).offset().top - hoverCardHeight;
    //                var finalPositionLeft = $(this).offset().left;

    //                $('.hovercard').css('background-image', 'url(/Images/ported/myKiltr/hovercardBackground.png)');
    //                $('.hovercard').show();
    //                $('.hovercard').css('z-index', '100000');
    //                $('.hovercard').css('top', finalTopLocation + 'px');
    //                $('.hovercard').css('left', finalPositionLeft + 'px');
    //                $('.hovercard').html('<img src="/Images/ported/ajax-loader-white.gif" class="hovercardAjaxLoader">');
    //                /* hovercard positioning stop*/

    //                if ($('#hovercardFiring').html() == 0) {
    //                    $('#hovercardFiring').html(1);
    //                    $.post("/Group/MiniProfile", {
    //                        groupId: groupFieldIdParts[1]
    //                    }, function (response) {
    //                        $('.hovercard').html(response);
    //                        $('#hovercardFiring').html(0);
    //                        $(".hovercardFooterNoClick").click(ShowGroupMembers);
    //                    });
    //                }
    //                return false;
    //            });
    //            if (hovercardFired == 0) {
    //                $(this).trigger("mouseover");
    //            }
    //        }
    //    });

    //    $('.hovercard').live('mouseleave', function () {
    //        $('.hovercard').hide();
    //        $('.hovercard').css('height', '150px');
    //    });

    /* things that can close the hovercard*/
    /*
    $('.cardRole, .cardLocation, img, .iconAction, .searchLocation, .cardRoleSmall, .messageMeaning, .profileCardImageSmall, .profileCardImage, .cardClose, .miniMessageImage, .messageEnding, .feedText > p, .feedReplyText > p, .feedImageSmall').live('mouseover', function () {
    */
    /*
    $('.cardRole, #accordion-sidebar-contacts, .cardLocation, img, .iconAction, .searchLocation, .cardRoleSmall, .messageMeaning, .profileCardImageSmall, .profileCardImage, .cardClose, .miniMessageImage, .messageEnding').live('mouseover', function () {
    $('.hovercard').hide();
    });
    */

    $('.cardRole, #accordion-sidebar-contacts, .cardLocation, .iconAction, .searchLocation').live('mouseover', function () {
        $('.hovercard').hide();
    });


    $('.profileCardImageSmall, .profileCardImage, .cardClose, .miniMessageImage, .messageEnding').live('mouseover', function () {
        $('.hovercard').hide();
    });

    $('.hovercardClose').live('click', function () {
        $('.hovercard').hide();
    });

    $('#seeMoreGroupRecommendations.seeMore').live('click', function () {

        var defaultPageSize = 4;
        var pageSizeDiv = $('#groupRecommendationsPageSize'); //page size		
        var pageSize = parseInt(pageSizeDiv.val());
        var currentHandle = $(this);
        var currentPageDiv = $('#groupRecommendationsCurrentPage'); //current page index

        var currentPage = parseInt(currentPageDiv.html()); // +1;
        //currentPageDiv.html(currentPage);

        if (currentPage * pageSize >= parseInt($('#groupRecommendationsTotalCount').val())) {
            $('#groupRecommendationsCurrentPage').html("1");
        }
        else {
            $('#groupRecommendationsCurrentPage').html(currentPage + 1);
        }


        if (pageSize < 80) {
            $('.seeMoreLink').hide();
            currentHandle.find('img').show();

            $.post("/MyKiltr/GetGroupRecommendations", {
                pageSize: defaultPageSize, //pageSize + defaultPageSize
                currentPage: currentPage
            }, function (response) {
                $('#groupRecommendationsContainer').html(response);
                currentHandle.find('img').hide();
                $('.seeMoreLink').show();
                //$('#totalGroupRecommendations').html($('#groupRecommendationsTotalCount').val());
            });
        }
        return false;
    });

    $('#seeMorePeopleRecommendations.seeMore').live('click', function () {
        //var defaultPageSize = 4;
        var pageSizeDiv = $('#peopleRecommendationsPageSize'); //page size		
        var pageSize = parseInt(pageSizeDiv.val());
        var currentHandle = $(this);

        var currentPageDiv = $('#peopleRecommendationsCurrentPage'); //current page index

        var currentPage = parseInt(currentPageDiv.html()); // +1;

        if (currentPage * pageSize >= parseInt($('#peopleRecommendationsTotalCount').val())) {
            $('#peopleRecommendationsCurrentPage').html("1");
        }
        else {
            $('#peopleRecommendationsCurrentPage').html(currentPage + 1);
        }

        if (pageSize < 80) {
            $('.seeMoreLink').hide();
            currentHandle.find('img').show();
            $.post("/MyKiltr/GetPeopleRecommendations", {
                pageSize: pageSize, //pageSize + defaultPageSize
                currentPage: currentPage //pageSize + defaultPageSize
            }, function (response) {
                $('#peopleRecommendationsContainer').html(response);
                currentHandle.find('img').hide();
                $('.seeMoreLink').show();
                //$('#totalPeopleRecommendations').html($('#peopleRecommendationsTotalCount').val());
            });
        }
        return false;
    });

    $('#seeMoreOrganisationRecommendations.seeMore').live('click', function () {

        var defaultPageSize = 4;
        var pageSizeDiv = $('#organisationRecommendationsPageSize'); //page size		
        var pageSize = parseInt(pageSizeDiv.val());
        var currentHandle = $(this);

        if (pageSize < 80) {
            $('.seeMoreLink').hide();
            currentHandle.find('img').show();

            $.post("/MyKiltr/GetOrganisationRecommendations", {
                pageSize: pageSize + defaultPageSize
            }, function (response) {
                $('#organisationRecommendationsContainer').html(response);
                currentHandle.find('img').hide();
                $('.seeMoreLink').show();
                $('#totalOrganisationRecommendations').html($('#organisationRecommendationsTotalCount').val());
            });
        }
        return false;
    });

    $('#seeMoreEventRecommendations.seeMore').live('click', function () {

        var defaultPageSize = 4;
        var pageSizeDiv = $('#eventRecommendationsPageSize'); //page size		
        var pageSize = parseInt(pageSizeDiv.val());
        var currentHandle = $(this);

        if (pageSize < 40) {
            currentHandle.find('img').show();
            $('.seeMoreLink').hide();
            $.post("/MyKiltr/GetEventRecommendations", {
                pageSize: pageSize + defaultPageSize
            }, function (response) {
                $('#eventRecommendationsContainer').html(response);
                currentHandle.find('img').hide();
                $('.seeMoreLink').show();
                $('#totalEventRecommendations').html($('#eventRecommendationsTotalCount').val());
            });
        }
        return false;
    });

    function CommentClickHandler() {
        var currentHandle = $(this);
        currentHandle.attr("disabled", "disabled");

        var loader = currentHandle.prev('.postCommentLoader');
        loader.show();
        var contentType = currentHandle.attr('id');
        var currentHandleParent = currentHandle.parent();   // postReplyTools
        var targetHandle = currentHandleParent.parent();    // feedItemReplyContainer
        var textBoxReply = targetHandle.find('.replyNonFocused');
        var postIdParts = targetHandle.attr('id').split('-');
        var postInsertPoint = targetHandle.find('.feedItemReplyLast');
        var commentCount = targetHandle.prev('.feedItem').find('.gestureComment');
        $.post("/Post/PostComment", {
            type: contentType,
            postId: postIdParts[1],
            hiddenLinkIntro: $('#hiddenLinkIntro-' + postIdParts[1]).val(),
            hiddenLinkThumbnail: $('#hiddenLinkThumbnail-' + postIdParts[1]).val(),
            hiddenLinkTitle: $('#hiddenLinkTitle-' + postIdParts[1]).val(),
            hiddenLinkUrl: $('#hiddenLinkUrl-' + postIdParts[1]).val(),
            audioUrl: $('#audioUrl-' + postIdParts[1]).val(),
            videoUrl: $('#videoUrl-' + postIdParts[1]).val(),
            attachmentIds: $('#attachmentIds-' + postIdParts[1]).val(),
            commentText: textBoxReply.val()
        }, function (response) {
            postInsertPoint.before(response);
            postInsertPoint.find('.replyNonFocused').css('height', '28px'); //15
            postInsertPoint.find('.replyNonFocused').css('width', '310px'); //324
            postInsertPoint.find('.replyNonFocused').css('margin', '0px');
            postInsertPoint.find('.replySimulatedContainer').css('height', '35px'); //67
            //$('#icons>.iconAction').css('background-position', ''); //not sure which is the most effective (does not work for replies)
            //$('#icons li').css('background-position', ''); //not sure which is the most effective (works for comments)
            $('#addImage, #addVideo, #addAudio, #addLink').css('background-position', ''); //not sure which is the most effective (works for comments)
            try {
                if (response != '' && response.split('|') != null && response.split('|')[0] == 'ADMIN') {
                    notifyUser(response.split('|')[1]);
                    currentHandle.removeAttr("disabled");
                    return;
                }
            } catch (e) { }

            textBoxReply.animate({
                height: '18px',
                easing: 'linear'
            }, 0, function () {
                // Animation complete.
                textBoxReply.css('color', '#D6D6D6');
                textBoxReply.val('');
            });

            incrementNumber(commentCount);
            var inputParent = textBoxReply.parent();
            var actionDiv = inputParent.find('.closeReplyPost');
            actionDiv.hide();

            $('.inlinePostToolbar').hide();
            $('.videoToolsDiv, .linkToolsDiv, .audioToolsDiv , .commentUploadTools').hide();

            startNetworkActivityFeed();
            loader.hide();
            currentHandle.removeAttr("disabled");
        });

        return false;

    }

    $('button.postComment').live('click', CommentClickHandler);

    $('.questionOverview').live('click', function () {
        $('.questionOverview').toggle();
    });

    $('.showMore').live('click', function () {
        $(this).prev('.revealable').slideDown(0);
        $(this).removeClass('showMore').addClass('showLess');
        $(this).html('less');
    });

    $('.showLess').live('click', function () {
        $(this).prev('.revealable').slideUp(0);
        $(this).removeClass('showLess').addClass('showMore');
        $(this).html('more');
    });

    $('.listItemButtons li').live('click', function () {
        $('.listItemButtons li').removeClass('alphaSelected');
        $('#contactContainer').html('<div class="accordionLoader"><img src="/Images/ported/genericInterface/white-ajax-loader.gif"></div>');

        $(this).addClass('alphaSelected');
        var letter = $(this).html();
        $('#currentLetter').html(letter);
        $.post("/MyKiltr/GetContactsByLastInitial", {
            letterToGet: letter
        }, function (response) {
            $('#contactContainer').html(response);
        });
    });

    //    $('.listBackButton').live('click', function () {
    //        $('#contactContainer').html('<div class="accordionLoader"><img src="/Images/ported/genericInterface/white-ajax-loader.gif"></div>');
    //        var currentLetter = $('#currentLetter').html();
    //        var currentPage = parseInt($('#currentPage').html());
    //        var totalPages = parseInt($('#totalPages').html());
    //        $.post("/Scripts/xhr/getContacts.aspx", {
    //            letterToGet: currentLetter,
    //            page: (currentPage - 1),
    //            maxPages: totalPages
    //        }, function (response) {
    //            $('#contactContainer').html(response);
    //            $('#currentPage').html(currentPage - 1);
    //        });
    //    });

    //    $('.listFwdButton').live('click', function () {
    //        $('#contactContainer').html('<div class="accordionLoader"><img src="/Images/ported/genericInterface/white-ajax-loader.gif"></div>');
    //        var currentLetter = $('#currentLetter').html();
    //        var currentPage = parseInt($('#currentPage').html());
    //        var totalPages = parseInt($('#totalPages').html());
    //        $.post("/Scripts/xhr/getContacts.aspx", {
    //            letterToGet: currentLetter,
    //            page: (currentPage + 1),
    //            maxPages: totalPages
    //        }, function (response) {
    //            $('#contactContainer').html(response);
    //            $('#currentPage').html(currentPage + 1);
    //        });
    //    });

    $('#savePageLayout').live('click', function () {
        $.post("/Scripts/xhr/saveLayout.aspx", {
            layout: 'l-r|profile-1|messages:2'
        }, function (response) {
            notifyUser(response);
        });
    });

    $('#restoreDefaults').live('click', function () {
        $.post("/Scripts/xhr/restoreDefaultLayout.aspx", {
        }, function (response) {
            notifyUser(response);
        });
    });

    if ($(".inlineFeed").size() > 0) {
        var idParts = $(".inlineFeed").attr('id').split("-");
        var userid = idParts[1];
        $('#chosenContext, .normal').hide();
        $('#selectedIds').val(userid + '|');
        $('#postContext').val('SelectContacts');
        $('#currentFeedLocation').val('User');
    }

    if ($(".inlineGroupFeed").size() > 0) {
        var idParts = $(".inlineGroupFeed").attr('id').split("-");
        var groupid = idParts[1];
        $('#chosenContext, .normal').hide();
        $('#selectedIds').val(groupid + '|');
        $('#postContext').val('SelectGroups');
        $('#currentFeedLocation').val('Group');
    }

    if ($(".inlineEventFeed").size() > 0) {
        var idParts = $(".inlineEventFeed").attr('id').split("-");
        var eventId = idParts[1];
        $('#chosenContext, .normal').hide();
        $('#selectedIds').val(eventId + '|');
        $('#postContext').val('SelectEvents');
        $('#currentFeedLocation').val('Event');
    }

    var isInProgress = false; //Prevent users spamming previos / next buttons

    $('#imageRight').click(function () {

        if (!isInProgress) {
            //Get/Set current image number
            var containerForCurrentNumber = $("#currentImageLink");
            var current = containerForCurrentNumber.html();
            var next = (parseInt(current) + 1);
            var containerForTotalNumber = $("#totalImagesLink");
            var total = containerForTotalNumber.html();
            containerForCurrentNumber.html(next);

            var distanceToTravel = ((parseInt(total) - 1) * 205);

            if (current == total) {
                var previewImageDiv = $('#linkPreviewImage div:nth-child(1) img');
                $('#hiddenLinkThumbnail').val(previewImageDiv.attr('src'));
                containerForCurrentNumber.html(1);

                isInProgress = true;
                $('#linkPreviewImage').animate({
                    marginLeft: '+=' + distanceToTravel + 'px'
                }, 2750, function () {
                    isInProgress = false;
                });

            } else {

                var previewImageDiv = $('#linkPreviewImage div:nth-child(' + next + ') img');
                $('#hiddenLinkThumbnail').val(previewImageDiv.attr('src'));
                containerForCurrentNumber.html(next);

                isInProgress = true;
                $('#linkPreviewImage').animate({
                    marginLeft: '-=205px'
                }, 750, function () {
                    isInProgress = false;
                });
            }
        }
    });



    $('#imageLeft').click(function () {

        if (!isInProgress) {
            //Get/Set current image number
            var containerForCurrentNumber = $("#currentImageLink");
            var current = containerForCurrentNumber.html();
            var previous = (parseInt(current) - 1);
            var containerForTotalNumber = $("#totalImagesLink");
            var total = containerForTotalNumber.html();
            containerForCurrentNumber.html(previous);


            if (current == 1) {
                var previewImageDiv = $('#linkPreviewImage div:nth-child(' + total + ') img');
                $('#hiddenLinkThumbnail').val(previewImageDiv.attr('src'));

                var distanceToTravel = ((parseInt(total) - 1) * 205);
                containerForCurrentNumber.html(total);
                isInProgress = true;
                $('#linkPreviewImage').animate({
                    marginLeft: '-=' + distanceToTravel + 'px'
                }, 2750, function () {
                    isInProgress = false;
                });

            } else {
                var previewImageDiv = $('#linkPreviewImage div:nth-child(' + previous + ') img');
                $('#hiddenLinkThumbnail').val(previewImageDiv.attr('src'));

                isInProgress = true;
                $('#linkPreviewImage').animate({
                    marginLeft: '+=205px'
                }, 750, function () {
                    isInProgress = false;
                });

            }
        }
    });

    $('.infoBox').live('mouseenter', function () {
        var infoBox = $(this).find('.infoBoxIcon');
        infoBox.css('background-position', '0px -33px');

    });

    $('.infoBox').live('mouseleave', function () {
        var infoBox = $(this).find('.infoBoxIcon');
        infoBox.css('background-position', '0px 0px');
    });

    $('.locationMatch,.userMatch').live('mouseenter', function () {
        $(this).find('.pickerVenueName').css('color', '#FFF');
        $(this).find('p').css('color', '#FFF');
    });

    $('.locationMatch,.userMatch').live('mouseleave', function () {
        $(this).find('.pickerVenueName').css('color', '#669ACC');
        $(this).find('p').css('color', '#000');
    });

    $('.imageLeft').live('click', function () {

        var parent = $(this).parent();
        var master = parent.parent();

        var currentImageDiv = parent.find('.currentImage');
        var current = currentImageDiv.html();

        var next = (parseInt(current) - 1);
        var linkPreviewImage = master.find('.linkPreviewImage');
        var idParts = linkPreviewImage.attr('id').split("-");
        var total = parent.find('.totalImages').html();

        currentImageDiv.html((parseInt(current) - 1));

        if (current == 1) {
            var previewImageDiv = $('#linkPreviewImage-' + idParts[1] + ' div:nth-child(' + total + ') img');
            $('#hiddenLinkThumbnail-' + idParts[1]).val(previewImageDiv.attr('src'));

            var distanceToTravel = ((parseInt(total) - 1) * 150);
            currentImageDiv.html(total);
            $('#linkPreviewImage-' + idParts[1]).animate({
                marginLeft: '-=' + distanceToTravel + 'px'
            }, 2750, function () {
            });

        } else {
            var previewImageDiv = $('#linkPreviewImage-' + idParts[1] + ' div:nth-child(' + next + ') img');
            $('#hiddenLinkThumbnail-' + idParts[1]).val(previewImageDiv.attr('src'));
            $('#linkPreviewImage-' + idParts[1]).animate({
                marginLeft: '+=150px'
            }, 750, function () {
            });

        }
    });

    $('.imageRight').live('click', function () {

        var parent = $(this).parent();
        var master = parent.parent();

        var currentImageDiv = parent.find('.currentImage');
        var current = currentImageDiv.html();
        var next = (parseInt(current) + 1);
        var linkPreviewImage = master.find('.linkPreviewImage');
        var idParts = linkPreviewImage.attr('id').split("-");
        var total = parent.find('.totalImages').html();
        var distanceToTravel = ((parseInt(total) - 1) * 150);

        if (current == total) {
            var previewImageDiv = $('#linkPreviewImage-' + idParts[1] + ' div:nth-child(1) img');

            $('#hiddenLinkThumbnail-' + idParts[1]).val(previewImageDiv.attr('src'));
            currentImageDiv.html(1);
            $('#linkPreviewImage-' + idParts[1]).animate({
                marginLeft: '+=' + distanceToTravel + 'px'
            }, 2750, function () {
            });

        } else {

            var previewImageDiv = $('#linkPreviewImage-' + idParts[1] + ' div:nth-child(' + next + ') img');
            $('#hiddenLinkThumbnail-' + idParts[1]).val(previewImageDiv.attr('src'));
            currentImageDiv.html((parseInt(current) + 1));

            $('#linkPreviewImage-' + idParts[1]).animate({
                marginLeft: '-=150px'
            }, 750, function () {
            });
        }
    });

    $('#shareLink').click(function () {

        var current = parseInt($('#currentImage').html());
        var chosenThumbnail = pageImages[(current - 1)];
        $('#linkTitle').val($('#linkPreviewTitle').html());
        $('#linkBody').val($('#linkPreviewIntro').html());
        $('#linkImage').val(chosenThumbnail);
        $('#linkUrl').val($('#linkPreviewUrl').html());

        $('#linkTools').hide(0, function () {
            $("#linkDialog").dialog({
                height: 140,
                modal: true
            });
        });

    });

    $('#newMessage,.newMessage').live('click', function () {    //TODO: Refactor .iconMessage, .sendContactMessage
        HideMiniProfile();          // TODO: Refactor into hiding function that takes a parameter telling you what not to hide
        $('.hovercard').hide();
        CloseGallery();

        var myDate = new Date();
        var dateParts = myDate.toString().split(" ");
        var dateString = $('#messageDate').text();
        styleMessageWindow();
        var reposition = (($(window).scrollTop()) + 45);

        $('#message').css('margin-top', reposition + 'px');
        $('#message').show();

        $("#message").draggable({ handle: '.modalHeader' });

        var actionIdParts = $(this).attr('id').split('-');
        var replacementText = $('#messageComposeBody').html();

        if ($('#messageComposeBody').html() != null) {
            var replacementText = replacementText.replace(/<p>/gi, "\n\n");
            var replacementText = replacementText.replace(/<\/p>/gi, "");
            var replacementText = replacementText.replace(/<br \/>/gi, "\n");
            var replacementText = replacementText.replace(/<br>/gi, "\n");
        }

        if (actionIdParts[0] == 'reply') {
            var currentStorageValue = $('#inputStorage').val();
            var senderId = $('.messageFrom').attr('id');
            var fromName = $('#fromName').html();
            $('.suggestableHidden').before('<div class="recipient" id="recipient-' + senderId + '"><div class="recipientName">' + fromName + '</div><div class="recipientCloseContainer"><img src="/Images/ported/messageCenter/recipientClose.gif" class="recipientClose"></div></div>');

            var subjectText = $('<div/>').html($('#messageTitle').html()).text();
            var subjectReplacementText = subjectText.replace(/Re: /gi, "");

            $('#messageSubject').val('Re: ' + subjectReplacementText);

            /*$('#messageSubject').val('Re: ' + $('<div/>').html($('#messageTitle').html()).text());*/
            $('#messageBody').val('\n\nAt ' + dateString + ', ' + fromName + ' said..' + $('<div/>').html(replacementText).text()).caret(0, 0); // strip_tags(replacementText));
            $('.inputStorage').val(senderId);
            $('#messageBody').focus();

        } else if (actionIdParts[0] == 'forward') {

            $('.inputStorage').val('');
            $('.recipient').remove();

            $('#messageSubject').val('Fwd: ' + $('<div/>').html($('#messageTitle').html()).text());
            $('#messageBody').val('\n\n ---- Forwarded message below ----' + $('<div/>').html(replacementText).text()); // strip_tags(replacementText));

        } else {
            $('.inputStorage').val('');
            $('.recipient').remove();
            $('#messageSubject').val('');
            $('#messageBody').val('');
        }
    });

    $('#donePicking').live('click', function () {

        var currentContext = $('#chosenContext').html();

        $('#emptyModalDialogue').hide();
        $('#selectedIds').val($('#selectedContacts').html());

        var contactsSelected = $('#selectedContacts').html().split("|");
        var updatedAmount = (contactsSelected.length - 1);

        if (updatedAmount == 0) {
            $('#chosenContext').html('All contacts');
        } else {
            $('#chosenContext').html(currentContext + ' (' + updatedAmount + ')');
        }

        updateSelectedContacts();
        updatedPickedQty();
    })

    $('.closeModalDialog').click(function () {
        $('#message, #locale, #emptyModalDialogue, #modalPrompt').hide();
        resetContext();
    });

    $('#confirmAction').live('click', function () {
        var currentValue = $('.intendedAction').html();
        var currentAction = $('.intendedAction').attr('id');
        var successMessage = $('#intendedActionSuccess').html();
        var overRideUrl = $('#ajaxOverride').html();
        var callback = $('#callback').html();

        if (overRideUrl == null) {
            $.post("/Ajax/HandleYesNo", {
                intendedAction: currentAction,
                intendedValue: currentValue
            }, function (response) {
                $('#modalPrompt').hide();
                if (successMessage != '') {
                    notifyUser(successMessage);
                } else if (response != '') {
                    notifyUser(response);
                }
                weePipe();    // not even required here for the two delete cases anyway - not checked the rest
                if (callback != null) {
                    eval(callback);
                }
            });
        } else {
            window.location.replace(overRideUrl);
        }
    });
    /*
    $('.main-feed-item-container').live('mouseenter',function(){
    var replyContainer = $(this).next('.feedItemReplyContainer');
    replyContainer.css('border-left', '5px solid #5493BF');
    });
    */
    $('#deleteAccount').live('click', function () {

        var reposition = (($(window).scrollTop()) + 45);
        $('#modalPrompt').css('margin-top', reposition + 'px');
        $('#promptMessage').html('Are you sure you want to delete your account?');
        $('.intendedAction').attr('id', 'deleteUser');
        //$('.intendedAction').html('The account is being deleted.');
        $('.promptTitle').html('Account Delete');
        $('#modalPrompt').show();
        $(".closeModalDialog").show(); //Force close cross to show
        return false;
    });

    $('#cancelAction').live('click', function () {
        $('#modalPrompt').hide();
    });

    $('.messageToHidden').keyup(function () {
        $('#messageFailureMessage').html('');
        var currentValue = $('.messageToHidden').val();
        $('#recipientSuggestions').css('left', $('.messageToHidden').position().left + 'px');

        if (currentValue == '') {
            $('#recipientSuggestions').hide();
        } else {
            $.post("/Scripts/xhr/getContactSuggestions.aspx", {
                matchCriteria: currentValue
            }, function (response) {
                $('#recipientSuggestions').html(response);
                $('#recipientSuggestions').show();
            });
        }
    });

    $('#editProfileIcon').live('click', function () {
        window.location.replace("/MyKiltr/EditProfile");
    });

    $('#messageSendButton').live('click', function () {
        var currentUrl = document.location.href;
        var urlParts = currentUrl.split('/');

        var parentDiv = $(this).parent();
        var parentDiv = parentDiv.parent();
        var suggestionDiv = parentDiv.find('.inputStorage');
        if ($('#messageBody').val() == '') {
            notifyUser('Oops, you must enter a message prior to clicking send.');
        } else {
            if (suggestionDiv.val() == '') {
                $('#messageFailureMessage').html('Please select at least one recipient');
            } else {

                var recipientString = suggestionDiv.val();
                var stringLength = recipientString.length;
                var lastChar = recipientString.substring((stringLength - 1));

                if (lastChar == '|') {
                    var userString = recipientString.substring(0, (stringLength - 1));
                } else {
                    var userString = suggestionDiv.val();
                }

                $('#messageLoader').show();

                $.post("/Message/SendMessage", {
                    recipients: userString,
                    subject: $('#messageSubject').val(),
                    messageBody: $('#messageBody').val()
                }, function (response) {
                    if (response == 1) {

                        $('#messageLoader').hide();
                        $('#message').fadeOut('500');

                        suggestionDiv.val('');
                        $('#messageSubject').val('');
                        $('#messageBody').val('');

                        notifyUser('Thank you, your message has been sent.');

                        if (urlParts[4] == 'ReadMessage') {
                            location.replace('/MyKiltr/Inbox');
                        }

                    } else {
                        $('#messageFailureMessage').html(response);
                        $('#messageLoader').hide();
                        notifyUser(response);
                    }
                    $.scrollTo('body', 1000);
                });
            }
        }
    });

    $('.suggestion').live('click', function () {
        var currentQtyRecipients = parseInt($('#recipientQty').html());
        var currentRecipients = $('#recipientList').html();
        var userid = $(this).attr('id');
        var useridparts = userid.split('-');

        if (userAlreadySelected(useridparts[1]) == false) {
            $('.messageToHidden').before('<div class="recipient" id="recipient-' + useridparts[1] + '"><div class="recipientName">' + $(this).html() + '</div><div class="recipientCloseContainer"><img src="/Images/ported/messageCenter/recipientClose.gif" class="recipientClose"></div></div>');
            $('#recipientQty').html(currentQtyRecipients + 1);
            resetSuggestion();
            resizeMessageWindow();

            if (currentRecipients == '') {
                $('#recipientList').html(useridparts[1]);
            } else {
                $('#recipientList').html(currentRecipients + '|' + useridparts[1]);
            }
        } else {
            resetSuggestion();
        }
    });

    $('html').click(function () {
        $('.itemSuggestions').hide();
    });


    $('.itemSuggestions').live('mouseleave', function () {
        $('.itemSuggestions').hide();
    });

    $('.suggestableHidden').live('keyup', function () {
        $('#messageFailureMessage').html('');
        var idParts = $(this).attr('id').split('-');
        var itemSuggestions = $(this).next('div');
        var currentValue = $(this).val();
        itemSuggestions.css('left', $(this).position().left + 'px');

        if (currentValue == '') {
            itemSuggestions.hide();
        } else {
            $.post("/Ajax/GetSuggestions", {
                suggestionType: idParts[1],
                matchCriteria: currentValue
            }, function (response) {
                itemSuggestions.html(response);
                itemSuggestions.css('z-index', '999999');
                itemSuggestions.show();
            });
        }
    });

    $('.itemSuggestion').live('click', function () {

        var suggestionList = $(this).parent();
        var suggestionListContainer = suggestionList.parent();
        var suggestionsDiv = suggestionListContainer.parent();

        var suggestableHiddenInput = suggestionsDiv.prev('.suggestableHidden');
        var itemQtyDiv = suggestionsDiv.next('div');
        var itemListDiv = itemQtyDiv.next('div');
        var containerBox = suggestableHiddenInput.parent();
        var itemHiddenField = containerBox.find('.inputStorage');

        var currentQty = parseInt(itemQtyDiv.html());
        var currentItems = itemHiddenField.val();
        var tagid = $(this).attr('id');
        var tagidparts = tagid.split('-');
        var currentInputBoxValue = suggestableHiddenInput.val();

        if (itemAlreadySelected(tagidparts[1], itemHiddenField) == false) {

            if (containerBox.attr('class') == 'messageInputLineInput') {
                /*
                containerBox.css('height','29px');
                */
                suggestableHiddenInput.css('padding-top', '10px');

                var entriesPerRow = 4;
                var initialHeight = 12;

                resizeMessageWindow(currentQty);

            } else {
                var entriesPerRow = 2;
                containerBox.css('height', '29px');
                suggestableHiddenInput.css('padding-top', '10px');
                var initialHeight = 29;
            }

            itemQtyDiv.html(currentQty + 1);

            resetItems();

            var outerContainerBox = containerBox.parent();

            suggestionsDiv.hide();
            suggestableHiddenInput.val('');
            suggestableHiddenInput.focus();


            var innerWindowOffset = 30;
            var newQty = parseInt(currentQty);
            var rows = Math.ceil((newQty + 2) / entriesPerRow);
            var heightAddition = ((rows - 1) * innerWindowOffset);

            var currentMessgeWindowHeight = containerBox.height();
            var newCurrentMessgeWindowHeight = heightAddition + initialHeight;

            outerContainerBox.animate({
                height: (newCurrentMessgeWindowHeight + initialHeight)
            }, 0, function () {
                containerBox.animate({
                    height: newCurrentMessgeWindowHeight
                }, 0, function () {
                });
            });

            if (tagidparts[1] == 'new') {
                $.post("/MyKiltr/AddNewTag", {
                    tagType: tagidparts[0],
                    tagId: tagidparts[1],
                    inputValue: currentInputBoxValue

                }, function (response) {
                    newTagId = response;
                    suggestableHiddenInput.before('<div class="recipient" id="item-' + response + '"><div class="recipientName">' + currentInputBoxValue + '</div><div class="recipientCloseContainer"><img src="/Images/ported/messageCenter/recipientClose.gif" class="itemClose"></div></div>');
                    if (currentItems == '') {
                        itemHiddenField.val(response);
                    } else {
                        itemHiddenField.val(currentItems + '|' + response);
                    }
                });

            } else {
                suggestableHiddenInput.before('<div class="recipient" id="item-' + tagidparts[1] + '"><div class="recipientName">' + $(this).html() + '</div><div class="recipientCloseContainer"><img src="/Images/ported/messageCenter/recipientClose.gif" class="itemClose"></div></div>');
                if (currentItems == '') {
                    itemHiddenField.val(tagidparts[1]);
                } else {
                    itemHiddenField.val(currentItems + '|' + tagidparts[1]);
                }
            }

            if (currentItems == '') {
                //remove next line eventually
                itemListDiv.html(tagidparts[1]);
                itemHiddenField.val(tagidparts[1]);
            } else {
                //remove next line eventually
                itemListDiv.html(currentItems + '|' + tagidparts[1]);
                itemHiddenField.val(currentItems + '|' + tagidparts[1]);
            }
        } else {
            suggestionsDiv.hide();
            suggestableHiddenInput.val('');
            suggestableHiddenInput.focus();
        }
    });

    $('.recipientClose').live('click', function () {

        var currentQtyRecipients = parseInt($('#recipientQty').html());
        var prevDiv = $(this).parent();
        var prevDiv = prevDiv.parent();
        var userString = '';
        var useridparts = prevDiv.attr('id').split('-');
        var currentRecipients = $('#recipientList').html();
        recipientsArray = currentRecipients.split('|');
        for (x in recipientsArray) {
            if (recipientsArray[x] != useridparts[1]) {
                if (recipientsArray[x] != '') {
                    userString = userString + recipientsArray[x] + '|';
                }
            }
        }
        $('#recipientList').html(userString);
        prevDiv.remove();
        $('#recipientQty').html(currentQtyRecipients - 1);
        resizeMessageWindow();
    });

    $('.others').live('click', function () {
        $('#emptyModalDialogue').show();
        return false;
    });

    $('.closeDisplay').live('click', function () {

        var prevDiv = $(this).parent();
        var prevDiv = prevDiv.parent();
        var currentContext = $('#postContext').val();

        var recipParentDiv = prevDiv.parent();
        var recipientQtyDiv = recipParentDiv.find('.itemQty');
        var currentQtyRecipients = parseInt(recipientQtyDiv.html());

        var itemListDiv = $('#selectedIds');

        var userString = '';
        var useridparts = prevDiv.attr('id').split('-');
        var currentRecipients = itemListDiv.val();
        recipientsArray = currentRecipients.split('|');
        var count = 0;

        for (x in recipientsArray) {
            if (recipientsArray[x] != useridparts[1]) {
                if (recipientsArray[x] != '') {
                    userString = userString + recipientsArray[x] + '|';
                }
                count++;
            }
        }

        var newQty = currentQtyRecipients;
        itemListDiv.val(userString);
        $('#selectedContacts').html(userString);
        $('#card-' + useridparts[1]).removeClass('cardSelected').addClass('card');
        prevDiv.remove();

        if (currentContext == 'SelectGroups') {
            contextDesc = 'Selected groups';
        } else if (currentContext == 'SelectContacts') {
            contextDesc = 'Selected contacts';
        } else if (currentContext == 'SelectOrganisations') {
            contextDesc = 'Selected organisations';
        } else if (currentContext == 'SelectEvents') {
            contextDesc = 'Selected events';
        } else {
            contextDesc = 'Selected';
        }

        $('#chosenContext').html(contextDesc + ' (' + (count - 1) + ')');
        recipientQtyDiv.html(currentQtyRecipients - 1);
        updateSelectedContacts();
    });

    $('.itemClose').live('click', function () {

        var prevDiv = $(this).parent();
        var prevDiv = prevDiv.parent();
        var recipParentDiv = prevDiv.parent();
        var recipientQtyDiv = recipParentDiv.find('.itemQty');
        var currentQtyRecipients = parseInt(recipientQtyDiv.html());
        var itemListDiv = recipParentDiv.find('.inputStorage');

        var userString = '';
        var useridparts = prevDiv.attr('id').split('-');
        var currentRecipients = itemListDiv.val();
        recipientsArray = currentRecipients.split('|');

        for (x in recipientsArray) {
            if (recipientsArray[x] != useridparts[1]) {
                if (recipientsArray[x] != '') {
                    userString = userString + recipientsArray[x] + '|';
                }
            }
        }
        var outerContainerBox = recipParentDiv.parent();
        var textBoxDiv = recipParentDiv.find('.suggestableHidden');

        var initialHeight = 29;
        var innerWindowOffset = 30;
        var newQty = currentQtyRecipients;
        var rows = Math.ceil((newQty + 1) / 3);
        var heightAddition = ((rows - 1) * 30);

        var currentMessgeWindowHeight = recipParentDiv.height();
        var newCurrentMessgeWindowHeight = heightAddition + initialHeight;

        if ((currentQtyRecipients - 1) == 0) {
            outerContainerBox.animate({
                height: '41px'
            }, 0, function () {
                recipParentDiv.animate({
                    height: '15px'
                }, 0, function () {
                    textBoxDiv.css('padding-top', '3px');
                    /*alert('text box is : '+textBoxDiv.attr('class')+' '+textBoxDiv.attr('id'));*/
                });
            });
        } else {

            outerContainerBox.animate({
                height: (newCurrentMessgeWindowHeight + initialHeight)
            }, 0, function () {
                recipParentDiv.animate({
                    height: newCurrentMessgeWindowHeight
                }, 0, function () {
                });
            });
        }

        itemListDiv.val(userString);

        prevDiv.remove();
        recipientQtyDiv.html(currentQtyRecipients - 1);
        resizeMessageWindow();
    });

    /*
    $(this).find(":last-child").css('color','#5A95BF');
    */

    function selectWidgetTab(clickedTab) {
        //initialize filter
        $('.alphaBiteOn').removeClass('alphaBiteOn').addClass('alphaBite');
        $('.alphaBiteAll').removeClass('alphaBiteAllOn').addClass('alphaBiteAllOn');
        $('#selectedContacts').html('');
        var currentId = clickedTab.attr('id');

        if (currentId != 'viewImportOptions' && currentId != 'addIndividualAddresses') {

            $('#selectedMode').html(currentId);
            var sectTitleHead = $('.sectTitleAlt');

            $('#contactDisplay').html('<div class="accordionLoader"><img src="/Images/ported/genericInterface/white-ajax-loader.gif"></div>');
            var postUrl;
            //alert(currentId);
            switch (currentId) {
                case 'viewSentInvites':
                    //postUrl = '/ContactImport/GetUsersImportedContactsInvited';
                    postUrl = '/ContactImport/GetSentInvites';
                    $('#pickerOptions').show();
                    $('#inviteControls').hide();
                    sectTitleHead.html('Invitations awaiting a response');
                    $('#deleteSelectedUserInvites').show();
                    $('#deleteSelectedImportedContacts').hide();
                    //$('#notYetInvitedTotals').hide();
                    $('#showAllImportedContacts').hide();
                    updateInvitedCount();
                    break;
                case 'viewnotYetInvited':
                    postUrl = '/ContactImport/GetUsersImportedContactsNotYetInvited';
                    $('#pickerOptions').show();
                    $('#inviteControls').show();
                    sectTitleHead.html('Select and invite your contacts to connect with you on KILTR');
                    $('#deleteSelectedUserInvites').hide();
                    $('#deleteSelectedImportedContacts').show();
                    //$('#notYetInvitedTotals').show();
                    $('#showAllImportedContacts').show();
                    updateImportedContactCount();

                    break;
                case 'viewAllConnections':
                    postUrl = '/MyKiltr/GetConnnections';
                    $('#pickerOptions').hide();
                    $('#inviteControls').hide();
                    sectTitleHead.html('Your current connections on KILTR');
                    break;
                case 'viewAllContacts':
                    postUrl = '/MyKiltr/PopulateAllContactsList';
                    $('#pickerOptions').hide();
                    $('#inviteControls').hide();
                    sectTitleHead.html('All of your imported contacts and connections on KILTR');
                    break;
                default:
                    return;
                    break;
            }

            $.post(postUrl, {
                contactType: currentId
            }, function (response) {
                $('#contactDisplay').html(response);
            });
        }

        return false;
    }


    $('.widgetTabLargeOn, .widgetTabLargeOff').live('click', function () {
        selectWidgetTab($(this));
    });

    $('.alphaBite').live('click', function () {
        //alert($('#selectedMode').html());
        $('#contactDisplay').html('<div class="accordionLoader"><img src="/Images/ported/genericInterface/white-ajax-loader.gif"></div>');
        $('.alphaBiteOn').removeClass('alphaBiteOn').addClass('alphaBite');
        $('.alphaBiteAllOn').removeClass('alphaBiteAllOn').addClass('alphaBiteAll');
        $(this).removeClass('alphaBite').addClass('alphaBiteOn');

        var selectedMode = $('#selectedMode').html();

        var postUrl;
        var letter = $(this).html();
        $('#currentLetter').html(letter);

        switch (selectedMode) {
            case 'viewSentInvites':
                postUrl = '/ContactImport/GetSentInvites';
                updateInvitedCount(letter);
                break;
            case 'viewnotYetInvited':
                postUrl = '/ContactImport/GetUsersImportedContactsNotYetInvitedByLastInitial';
                updateImportedContactCount(letter);
                break;
            case 'viewAllConnections':
                postUrl = '/MyKiltr/GetContactsByLastInitial';
                break;
            case 'viewAllContacts':
                postUrl = '/MyKiltr/PopulateAllContactsListByLastInitial';
                break;
            default:
                break;
        }

        $.post(postUrl, {
            letterToGet: letter
        }, function (response) {
            $('#contactDisplay').html(response);
        });
    });

    $('.alphaBiteAll').live('click', function () {
        $('#contactDisplay').html('<div class="accordionLoader"><img src="/Images/ported/genericInterface/white-ajax-loader.gif"></div>');
        $('.alphaBiteOn').removeClass('alphaBiteOn').addClass('alphaBite');
        $(this).addClass('alphaBiteAllOn');

        var postUrl;
        var selectedMode = $('#selectedMode').html();

        switch (selectedMode) {
            case 'viewSentInvites':
                postUrl = '/ContactImport/GetSentInvites';
                $('#pickerOptions').show();
                $('#inviteControls').hide();
                updateInvitedCount();
                break;
            case 'viewnotYetInvited':
                postUrl = '/ContactImport/GetUsersImportedContactsNotYetInvited';
                $('#pickerOptions').show();
                $('#inviteControls').show();
                updateImportedContactCount();
                break;
            case 'viewAllConnections':
                postUrl = '/MyKiltr/GetConnnections';
                $('#pickerOptions').hide();
                $('#inviteControls').hide();
                break;
            case 'viewAllContacts':
                postUrl = '/MyKiltr/PopulateAllContactsList';
                $('#pickerOptions').hide();
                $('#inviteControls').hide();
                break;
            default:
                break;
        }

        $.post(postUrl, function (response) {
            $('#contactDisplay').html(response);
        });
    });

    /* minimail functions */

    $('#inboxLoader').click(function () {
        $('#mailLoader').show();
        $.post("/Message/GetMiniMessageWidgetContent", {
            retrievalType: 'received'
        }, function (response) {
            $('#inboxLoader').attr('class', 'widgetTabOn');
            $('#sentboxLoader').attr('class', 'widgetTabOff');
            $('#miniMessages').html(response);
            $('#mailLoader').hide();
        });
        return false;
    });


    $('#sentboxLoader').click(function () {
        $('#mailLoader').show();
        $.post("/Message/GetMiniMessageWidgetContent", {
            retrievalType: 'sent'
        }, function (response) {
            $('#sentboxLoader').attr('class', 'widgetTabOn');
            $('#inboxLoader').attr('class', 'widgetTabOff');
            $('#miniMessages').html(response);
            $('#mailLoader').hide();
        });
        return false;
    });


    $('.actionIcon').mouseover(function () {
        var iconImg = $(this).find('div');
        iconImg.show();
    });

    $('.actionIcon').mouseout(function () {
        var iconImg = $(this).find('div');
        iconImg.hide();
    });

    $('.iconConnectionStatus').live('mouseover', function () {
        var iconImg = $(this).find('div');
        iconImg.show();
    });

    $('.iconConnectionStatus').live('mouseleave', function () {
        var iconImg = $(this).find('div');
        iconImg.hide();
    });

    //Control timing of mouseover
    var timeOut;

    $('.iconAction, .iconActionWide, .iconDumbAction').live('mouseover', function () {  //Binding hover inside mouseover was causing the first hover to fail.
        //$('.iconAction, .iconActionWide, .iconDumbAction').bind("hover", { speed: 200, delay: 500 }, function () {

        clearInterval(timeOut);

        var iconImg = $(this).find('div');

        timeOut = setTimeout(function () {
            if ($(this).attr("id") != undefined) { //Only check for parts if there are any!
                var itemParts = $(this).attr('id').split("-");
                if (itemParts[1] == 'report') {

                    iconImg.css('background-image', 'url(/Images/ported/actionIcons/speechBubble_red.gif)');
                }
            }
            iconImg.show();
        }, 500);
        //});
    });

    $('.iconAction, .iconActionWide, .iconDumbAction').live('mouseleave', function () {
        clearInterval(timeOut);
        var iconImg = $(this).find('div');
        iconImg.hide();
    });

    $('.floatingNavIcon, .floatingNavIconWide').live('mouseover', function () {

        var iconImg = $(this).find('div');
        iconImg.css('z-index', '9999999999');
        iconImg.show();
    });

    $('.floatingNavIcon, .floatingNavIconWide').live('mouseleave', function () {
        var iconImg = $(this).find('div');
        iconImg.hide();
    });

    $('.navDiscOff').live('click', function () {

        $('.navDiscOn').removeClass('navDiscOn').addClass('navDiscOff');
        $(this).removeClass('navDiscOff').addClass('navDiscOn');
        var slideInfo = $(this).attr('id');
        var slideInfoParts = slideInfo.split('-');
        var slidePosition = (parseInt(slideInfoParts[1]) * 880)
        $('#slideTrack').animate({
            marginLeft: "-" + slidePosition + "px"
        }, 1000);
    });


    /*$('.searchResultControl a').live('click',function(){
    var href = $(this).attr('href');
    $.get(href, function(response){     		
    $('#userSearchResults').html(response);
    });
    return false; 
    });*/

    $('a#contactImportInstructionLink').live('click', function () {
        $('#emptyModalDialogue').show();
        $('.modalHeader').html('How to create a contact file');

        var href = $(this).attr('href');
        $.get(href, function (response) {
            $('#emptyModalWindowBody').html(response);
        });
        return false;
    });

    $('#headerSearchForm').live('submit', function () {

        if ($('#searching').val() == 0) {
            $('#searching').val(1);

            $('#keywordSearchButton').attr('src', '/Images/ported/ajax-loader-find.gif');
            var searchType = $('#selectedSearchOption').val();
            var searchUrl = '';

            if ((searchType == 'peopleSearch') || (searchType == '')) {
                searchUrl = "/People/Search";
            }
            else if (searchType == 'organisationSearch') {
                searchUrl = "/Network/Search";
            }
            else if (searchType == 'eventSearch') {
                searchUrl = "/Event/Search";
            }
            else if (searchType == 'groupSearch') {
                searchUrl = "/Group/Search";
            }
            else {
                alert("search type: " + searchType + " not currently supported");
                return false;
            }

            var myForm = $('#headerSearchForm');
            myForm.attr('action', searchUrl);
            myForm.submit();
            return false;
        }

    });

    $('.floatingNavOptions').click(function () {

        jQuery.browser

        var parentContainer = $(this).parent();
        var optionsNav = parentContainer.prev('div');
        var floatingNavGroupDiv = optionsNav.next('div');
        var barWidth = parseInt(optionsNav.width());
        var endBitWidth = 8;
        $('.floatingNavSubMaster').animate({
            left: "0px"
        }, 200, function () {
            optionsNav.animate({ "left": (barWidth - endBitWidth) + "px" }, 200);
        });

    });

    $('.floatingNavSubMaster').mouseleave(function () {
        $('.floatingNavSubMaster').animate({ left: "0px" }, 200);
    });

    $('.floatingNavIcon').click(function () {
        $('.floatingNavSubMaster').animate({ left: "0px" }, 200);
    });

    $('.closeFloat,.floatingNavSubMaster > img,').click(function () {
        $('.floatingNavSubMaster').animate({ left: "0px" }, 200);
    });

    $('#returnToTop').click(function () {
        $.scrollTo('#outerContainerLoggedIn', 2000, { onAfter: function () {
            $("#accordion").accordion("option", "active", -1);
            $("#accordionSmall").accordion("option", "active", -1);
        }
        });
    });

    $('.connectionRequest, .connectFromGesture').live('click', function () {
        $('#popupInviteMessage').html('Hi, I would like to connect with you on KILTR.');
        $('.hovercard').hide();
        $('#emptyModalWindowBody').html('<img id=\'gallery-post-loader\' src=\'/Images/ported/ajax-loader-white.gif\' style=\"text-align:center;margin: 0 auto;\">');

        var reposition = (($(window).scrollTop()) + 35);

        $('#emptyModalDialogue').css('margin-top', reposition + 'px');
        $('.modalHeader').html('Send invite to connect');
        var idParts = $(this).attr('id').split('-');
        var bodyWidth = 725;
        if (idParts[1] == "addToContactExternal") bodyWidth = 480;
        $('#emptyModalWindow').css('height', '500px');
        $('#emptyModalWindow').css('width', (bodyWidth + 65) + 'px');
        $('#emptyModalWindowOverlay').css('height', '470px');
        $('#emptyModalWindowOverlay').css('width', (bodyWidth + 35) + 'px');
        $('#emptyModalWindowBody').css('width', (bodyWidth) + 'px');
        $("#emptyModalDialogue").draggable({ handle: '.modalHeader' });
        $('.modalHeader').css('width', '80%');
        $('#emptyModalDialogue').show();

        $.get("/Ajax/Connect", {
            userId: idParts[2],
            type: idParts[1]
        }, function (response) {
            $('#emptyModalWindowBody').html(response);

        });

        return false;
    });

    $('.howCheck').live('change', function () {
        $('.sendInviteViaPopup').fadeIn(300);
    });

    $('.sendInviteViaPopup').live('click', function () {
        var idparts = $(this).attr('id').split('-');

        $.post("/Invite/SendInvite", {
            connectionType: idparts[1],
            connectionReason: $('input[name=howDidYouKnow]:checked').val(),
            connectionMessage: $('#popupInviteMessage').val(),
            connectionId: idparts[2]
        }, function (response) {
            $('#emptyModalDialogue').hide();
            if (response == 1) {
                notifyUser('Thank you, your connection request has been sent');
            } else {
                notifyUser(response);
            }
        });
    });

    /*
    $('.connectionRequest').live('click', function () {

    var idparts = $(this).attr('id').split('-');
    var clickedDiv = $(this);
    var parentDiv = $(this).parent();

    var parentTemp = parentDiv.parent();
    var indicator = parentTemp.find('#contactIndicator');

    if (indicator.attr('id') == 'contactIndicator') {
    var nextDiv = indicator.find('.multiMaxSpeechIcon');
    var bubbleCopy = nextDiv.html();
    var newCopy = bubbleCopy.replace("is a contact", "has been invited");
    indicator.attr('id', 'inviteIndicator');
    nextDiv.html(newCopy);
    }

  
    $.post("/Invite/SendInvite", {
    connectionType: idparts[1],
    connectionId: idparts[2]
    }, function (response) {
    $('.hovercard').hide();
    if (response == 1) {
    notifyUser('Thank you, your connection request has been sent');
    clickedDiv.hide();
    if (parentDiv.attr('class') == 'connectionsLink') {
    parentDiv.hide();
    }
    } else {
    notifyUser(response);
    }
    });
    return false;
    });
    */
    /* contact picker card functionality start */

    $('.card').live('click', function () {

        var idParts = $(this).attr('id').split("-");
        var currentString = $('#selectedContacts').html();
        var newString = currentString + idParts[1] + '|';
        var cardName = $(this).find('.cardName');
        var cardName = cardName.find('strong');
        var curHtml = $('#selectedVisualDisplay').html();
        var msg = curHtml + '<div class="recipient recipientAlt" id="item-' + idParts[1] + '"><div class="recipientName">' + cardName.html() + '</div><div class="recipientCloseContainer"><img src="/Images/ported/messageCenter/recipientClose.gif" class="closeDisplay"></div></div>';
        $('#selectedVisualDisplay').show();
        $('#selectedVisualDisplay').html(msg);
        /*alert(cardName.html());*/

        $(this).removeClass('card').addClass('cardSelected');

        var currentlySelected = currentString.split('|');
        if (currentlySelected[0] == 'ALL') {
            var newString = '';
            for (var sIndex in currentlySelected) {
                var sValue = currentlySelected[sIndex];
                if (sValue != idParts[1]) {
                    if (sValue != '') {
                        newString += sValue + '|';
                    }
                }
            }
            $('#selectedContacts').html(newString);
            $('#selectedContactsCount').html(1 + parseInt($('#selectedContactsCount').html()));
        } else {
            $('#selectedContacts').html(newString);
            updateSelectedContacts();
        }


    });

    $('.cardSelected').live('click', function () {

        var idParts = $(this).attr('id').split("-");
        var currentlySelected = $('#selectedContacts').html().split("|");
        var newString = '';
        for (var sIndex in currentlySelected) {

            var sValue = currentlySelected[sIndex];
            if (sValue != idParts[1]) {
                if (sValue != '') {
                    newString += sValue + '|';
                }
            }
        }
        $('#item-' + idParts[1]).remove();
        $('#selectedContacts').html(newString);
        $(this).removeClass('cardSelected').addClass('card');

        var currentSelected = $('#selectedContacts').html().split('|');
        if (currentSelected[0] == 'ALL') {
            var currentSelectedContacts = $('#selectedContacts').html();
            $('#selectedContacts').html(currentSelectedContacts + idParts[1] + '|');
            $('#selectedContactsCount').html(parseInt($('#selectedContactsCount').html()) - 1);
        } else {
            updateSelectedContacts();
        }
    });

    $('#selectAll').live('click', function () {
        $('.card').removeClass('card').addClass('cardSelected');
        $('#selectedContacts').html('ALL|');
        $('#selectedContactsCount').html($('#importedContactTotal').html());
    });

    $('#unSelectAll').live('click', function () {
        $('.cardSelected').removeClass('cardSelected').addClass('card');
        updateSelectedContacts();
    });

    $('#deleteSelected').live('click', function () {
        $('.cardSelected').remove();
        updateSelectedContacts();
        //need to call delete here
    });

    function showAllInvitedContacts(callBack) {
        $.post('/ContactImport/GetSentInvites', function (response) {
            $('#contactDisplay').html(response);
            if (typeof (callBack) == 'function') {
                callBack();
            }
        });

        return false;
    }

    function showAllImportedContacts(callBack) {
        currentLetter = $('.alphaBiteOn').html();
        $.post('/ContactImport/GetAllUsersImportedContactsNotYetInvited', {
            contactType: 'viewnotYetInvited',
            currentLetter: currentLetter
        }, function (response) {
            $('#contactDisplay').html(response);
            if (typeof (callBack) == 'function') {
                callBack();
            }
        });

        return false;
    }

    function updateImportedContactCount(letter) {

        if (letter == null || letter == '') {
            $.post("/ContactImport/GetTotalNotYetInvitedCount", function (response) {
                $('#importedContactTotal').html(response);
                $('#selectedContactsCount').html("0");
            });
        }
        else {

            $.post("/ContactImport/GetTotalNotYetInvitedCountByInitial", {
                letterToGet: letter
            },
            function (response) {
                $('#importedContactTotal').html(response);
                $('#selectedContactsCount').html("0");
            });
        }
    }

    function updateInvitedCount(letter) {
        if (letter == null || letter == '') {
            $.post("/ContactImport/GetTotalInvitedCount", function (response) {
                $('#importedContactTotal').html(response);
                $('#selectedContactsCount').html("0");
            });
        }
        else {
            $.post("/ContactImport/GetTotalInvitedCountByInitial", {
                letterToGet: letter
            },
            function (response) {
                $('#importedContactTotal').html(response);
                $('#selectedContactsCount').html("0");
            });
        }
    }

    $('#showAllImportedContacts').live('click', showAllImportedContacts);


    $('#deleteSelectedImportedContacts').live('click', function () {

        var idsToDelete = $('#selectedContacts').html();

        if (idsToDelete == '') {
            notifyUser('No contacts selected');
            return;
        }

        $.post('/ContactImport/Delete', { importedContactIds: idsToDelete }, function (response) {
            $('#contactDisplay').html('');
            selectWidgetTab($('#viewnotYetInvited'));
            notifyUser('Imported contacts successfully deleted');
        });
        $('#contactDisplay').html('<div class="accordionLoader"><img src="/Images/ported/genericInterface/white-ajax-loader.gif"></div>');

        //  $('.cardSelected').remove();
        //    if ($('.seeMoreItems').is(":visible"))
        //        loadMore($('.seeMoreItems'));
    });

    $('#deleteSelectedUserInvites').live('click', function () {
        var idsToDelete = $('#selectedContacts').html();

        //    $('.cardSelected').each(function (index) {
        //        idParts = $(this).attr('id').split("-")
        //        idsToDelete += idParts[1] + '|';
        //    });

        if (idsToDelete == '') {
            notifyUser('No invites selected');
            return;
        }

        $.post('/ContactImport/DeleteUserInvites', { userInviteIds: idsToDelete });
        $('.cardSelected').remove();
        updateSelectedContacts();
        updateInvitedCount();
        notifyUser('User invites successfully deleted');
    });

    /* contact picker card functionality end */

    $('.decisionAccept').live('click', function () {
        var parentDiv = $(this).parent();
        var idParts = parentDiv.attr('id').split("-");
        $.post("/Scripts/xhr/connectionRequest.aspx", {
            decisionType: 'accept',
            requestId: idParts[1]
        }, function (response) {
            if (response == 1) {
                notifyUser('Thank you, request accepted');
                $(this).prev('.messageSummary').hide();
            } else {
                notifyUser(response);
            }
        });
    });

    $('.decisionDecline').live('click', function () {
        var parentDiv = $(this).parent();
        var idParts = parentDiv.attr('id').split("-");
        $.post("/Scripts/xhr/connectionRequest.aspx", {
            decisionType: 'decline',
            requestId: idParts[1]
        }, function (response) {
            if (response == 1) {
                notifyUser('Thank you, request declined');
            } else {
                notifyUser(response);
            }
        });
    });

    $('.decisionAttending').live('click', function () {
        var parentDiv = $(this).parent();
        var idParts = parentDiv.attr('id').split("-");
        $.post("/Scripts/xhr/connectionRequest.aspx", {
            decisionType: 'attending',
            requestId: idParts[1]
        }, function (response) {
            if (response == 1) {
                notifyUser('Thank you, event attendance acknowledged.');
            } else {
                notifyUser(response);
            }
        });
    });

    $('.eventAttendance, #eventNotInvited').live('click', function () {
        $('.cardPicker').html('<div class="loading"></div>');
        $('#selectedContacts').html('');
        $('#pickerOptions').show();
        $('.widgetTabOn').removeClass('widgetTabOn').addClass('widgetTabOff');
        $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        $.post("/Event/GetInvitees", {
            response: $(this).attr('id'),
            groupId: $('#entityId').html()
        }, function (response) {
            $('.cardPicker').html(response);
            $(this).find('span').html($('#listCount').val());
            $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        });
    });

    $('#getParticipating').live('click', function () {
        $('.cardPicker').html('<div class="loading"></div>');
        $('#selectedContacts').html('');
        $('#pickerOptions').show();
        $('.widgetTabOn').removeClass('widgetTabOn').addClass('widgetTabOff');
        $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        $.post("/Group/GetUsersAcceptedInviteCount", {
            groupId: $('#entityId').html()
        }, function (response) {
            $('#participatingCount').html(response);
        });
        $.post("/Group/GetUsersAcceptedInvite", {
            mode: 'participating',
            groupId: $('#entityId').html()
        }, function (response) {
            $('.cardPicker').html(response);
            $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
            //$('.card').removeClass('card').addClass('cardSelected');
        });
    });

    $('#getNotParticipating').live('click', function () {
        $('.cardPicker').html('<div class="loading"></div>');
        $('#selectedContacts').html('');
        $('#pickerOptions').show();
        $('.widgetTabOn').removeClass('widgetTabOn').addClass('widgetTabOff');
        $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        $.post("/Group/GetUsersDeclinedInviteCount", {
            groupId: $('#entityId').html()
        }, function (response) {
            $('#declinedCount').html(response);
        });
        $.post("/Group/GetUsersDeclinedInvite", {
            mode: 'notParticipating',
            groupId: $('#entityId').html()
        }, function (response) {
            $('.cardPicker').html(response);
        });
    });

    $('#getNotYetReplied').live('click', function () {
        $('.cardPicker').html('<div class="loading"></div>');
        $('#selectedContacts').html('');
        $('#pickerOptions').show();
        $('.widgetTabOn').removeClass('widgetTabOn').addClass('widgetTabOff');
        $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        $.post("/Group/GetUsersNotRespondedInviteCount", {
            groupId: $('#entityId').html()
        }, function (response) {
            $('#notYetRepliedCount').html(response);
        });
        $.post("/Group/GetUsersNotRespondedInvite", {
            mode: 'notYetReplied',
            groupId: $('#entityId').html()
        }, function (response) {
            $('.cardPicker').html(response);
            $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        });
    });

    $('#notYetInvited').live('click', function () {
        $('.cardPicker').html('<div class="loading"></div>');
        $('.sectTitle').html('Add a personal message to your invite');
        $('#selectedContacts').html('');
        $('#pickerOptions').show();
        $('.widgetTabOn').removeClass('widgetTabOn').addClass('widgetTabOff');
        $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        $.post("/Group/GetUsersNotYetInvitedCount", {
            groupId: $('#entityId').html()
        }, function (response) {
            $('#notYetInvitedCount').html("(" + response + ")");
        });
        $.post("/Group/GetUsersNotYetInvited", {
            mode: 'notYetInvited',
            groupId: $('#entityId').html()
        }, function (response) {
            $('.cardPicker').html(response);
            $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        });
    });

    $('#getRequestsToJoin').live('click', function () {
        $('.cardPicker').html('<div class="loading"></div>');
        $('#selectedContacts').html('');
        $('#pickerOptions').show();
        $('#acceptSelectedRequests').show();
        $('.widgetTabOn').removeClass('widgetTabOn').addClass('widgetTabOff');
        $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        $.post("/Group/GetUsersGroupInviteRequests", {
            mode: 'getRequestsToJoin',
            groupId: $('#entityId').html()
        }, function (response) {
            $('.cardPicker').html(response);
            //$('#requestsToJoinCount').html($('#listCount').val());
            $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
        });
    });

    $('#messageSelectedUsers').live('click', function () {
        var uri;
        var recipients = $('#selectedContacts').html();
        if (recipients != 0) {
            if ($('#messageMode').val() == 'invite') {
                uri = '/Group/SendInvites';
                $('.cardPicker').html('<div class="loading"></div>');
            } else if ($('#messageMode').val() == 'eventInvite') {
                uri = '/Event/SendInvites';
                $('.cardPicker').html('<div class="loading"></div>');
            } else if ($('#messageMode').val() == 'eventMessage') {
                uri = '/Event/SendMessage';
            } else {
                uri = '/Group/SendGroupMessage';
            }

            $.post(uri, {
                groupId: $('#entityId').html(),
                entityType: $('#entityType').html(),
                recipients: $('#selectedContacts').html(),
                messageMode: $('#messageMode').val(),
                message: $('#individualContactMessage').val()
            }, function (response) {
                if (response != "1") {
                    $('.cardPicker').html(response);
                }
                if ($('#messageMode').val() == 'invite') {
                    notifyUser('Thank you, your invites have been sent.');
                } else {
                    notifyUser('Thank you, your message has been sent.');
                }
            });
        } else {
            notifyUser('Please select at least one recipient.');
        }
    });

    $('#getParticipating, #getNotParticipating, #getNotYetReplied').live('click', function () {
        $('#messageMode').val('message');
        $('#deleteSelectedContacts').show();
    });

    $('#getParticipating, #getNotParticipating, #getNotYetReplied, #getRequestsToJoin').live('click', function () {
        $('.sectTitle').html('Send selected members a message');
    });

    $('.eventAttendance').live('click', function () {
        $('#messageMode').val('eventMessage');
        $('#deleteSelectedContacts').show();
        $('.sectTitle').html('Send selected invitees a message');
    });

    $('#getParticipating, #getNotParticipating, #getNotYetReplied, #notYetInvited').live('click', function () {
        $('#acceptSelectedRequests').hide();
    });

    $('#notYetInvited').live('click', function () {
        $('#messageMode').val('invite');
    });

    $('#eventNotInvited').live('click', function () {
        $('#messageMode').val('eventInvite');
    });

    $('#notYetInvited, #eventNotInvited').live('click', function () {
        $('.sectTitle').html('Add a personal message to your invite');
        $('#deleteSelectedContacts').hide();
    });

    $('.decisionNotAttending').live('click', function () {
        var parentDiv = $(this).parent();
        var idParts = parentDiv.attr('id').split("-");
        $.post("/Scripts/xhr/connectionRequest.aspx", {
            decisionType: 'notAttending',
            requestId: idParts[1]
        }, function (response) {
            if (response == 1) {
                notifyUser('Thank you, event attendance acknowledged.');
            } else {
                notifyUser(response);
            }
        });
    });

    $('.decisionMightAttend').live('click', function () {
        var parentDiv = $(this).parent();
        var idParts = parentDiv.attr('id').split("-");
        $.post("/Scripts/xhr/connectionRequest.aspx", {
            decisionType: 'mightAttend',
            requestId: idParts[1]
        }, function (response) {
            if (response == 1) {
                notifyUser('Thank you, event attendance acknowledged.');
            } else {
                notifyUser(response);
            }
        });
    });

    //setInterval(checkInviteProgress, 2000);
    //function checkInviteProgress() {
    //    if ($('#inviteProgress') == null || $('#inviteProgress').html() == null || $('#inviteProgress').html() == "") {
    //        return false;
    //    }
    //    //alert($('#inviteProgress').html());
    //    $.get("/ContactImport/GetInviteProgress", { session: $('#sessionId').html() }, function (response) {
    //        if (response == 'Complete') {
    //            $('#inviteProgress').html('');
    //            $('.cardPicker').fadeOut(500);
    //            selectWidgetTab($('#viewnotYetInvited'));
    //            notifyUser('Thank you, contact invitations sent successfully.');
    //            $('#contactImportLoader').hide();
    //            $('#sendInvites').show();
    //            $('.cardSelected').remove();
    //            updateImportedContactCount();
    //        } else {
    //            //alert(response);
    //            $('#inviteProgress').html('Invitations sent: ' + response);
    //            //setTimeout('checkInviteProgress()', 1000);
    //        }
    //    });
    //}


    $('#sendInvites').live('click', function () {

        $('#sendInvites').hide();
        $('#contactImportLoader').show();
        //$('#inviteProgress').show();
        var currentRecipients = $('#selectedContacts').html();

        var inviteMessage = $('.inviteContactMessage').val();
        if (currentRecipients.length > 0) {
            $.post("/ContactImport/InviteImportedContactsToConnect", {
                recipients: currentRecipients,
                message: inviteMessage
            }, function (response) {
                if (response == "1") {
                    $('.cardPicker').fadeOut(500);
                    selectWidgetTab($('#viewnotYetInvited'));
                    notifyUser('Thank you, contact invitations sent successfully.');
                    $('#contactImportLoader').hide();
                    $('#sendInvites').show();
                    $('.cardSelected').remove();
                    updateImportedContactCount();
                }
                else {
                    notifyUser("There was a problem sending your invites.");
                }
            });
        } else {
            notifyUser('No contacts selected.');
            $('#contactImportLoader').hide();
            $('#sendInvites').show();
        }
    });

    $('#sendIndividualInvites').live('click', function () {
        $('#individualInvitesLoader').show();
        $.post("/ContactImport/InviteEmailAddressesToConnect", {
            email1: $('#email1').val(),
            email2: $('#email2').val(),
            email3: $('#email3').val(),
            email4: $('#email4').val(),
            email5: $('#email5').val(),
            individualContactMessage: $('#individualContactMessage').val()
        }, function (response) {
            if (response == 1) {
                $('#email1').val('');
                $('#email2').val('');
                $('#email3').val('');
                $('#email4').val('');
                $('#email5').val('');
                notifyUser('Thank you, your invites have been sent, enter more email addresses to continue.');
            } else {
                notifyUser('Please enter email addresses to invite.');
            }
            $('#individualInvitesLoader').hide();
        });
    });


    /*MyKILTR Contact Import user search*/
    $('#peopleSearchButton').live('click', function () {
        $('#peopleSearchLoader').show();
        $.post("/Search/AdvancedUserSearch", {
            firstName: $('#firstName').val(),
            lastName: $('#lastName').val(),
            emailAddress: $('#emailAddress').val(),
            organisation: $('#organisation').val(),
            academicInstitution: $('#academicInstitution').val()
        }, function (response) {
            $('#peopleSearchLoader').hide();
            $('.searchResultsWide').html(response);

        });
    });


    $('.searchResult,.searchResultWide').live('mouseenter', function () {
        var cardDiv = $(this).find('.cardActionBar');
        cardDiv.show();
    });

    $('.searchResult,.searchResultWide').live('mouseleave', function () {
        var cardDiv = $(this).find('.cardActionBar');
        cardDiv.hide();
    });

    $('.simpleItem,.searchResultWide').live('mouseenter', function () {
        var cardDiv = $(this).find('.cardActionBar');
        cardDiv.show();
    });

    $('.simpleItem,.searchResultWide').live('mouseleave', function () {
        var cardDiv = $(this).find('.cardActionBar');
        cardDiv.hide();
    });

    $('#AccessType-1').live('click', function () {
        $('.inlineCheckBoxContainer #EnablePublicProfile').parent().show();
    });

    $('#AccessType-2').live('click', function () {
        $('.inlineCheckBoxContainer #EnablePublicProfile').parent().hide();
    });

    $('#updateOrganisation').live('click', function () {
        $('#saveFormLoader').show();
        $.post("/Scripts/xhr/saveOrganisation.aspx", {
            currentLocationData: $('#currentLocationHidden').val(),
            name: $('#name').val(),
            image: $('#attachmentIds').val(),
            groupType: $('#groupType').val(),
            accessType: $('#accessType').val(),
            groupSummary: $('#groupSummary').val(),
            groupDescription: $('#groupDescription').val(),
            websiteUrl: $('#websiteUrl').val()
        }, function (response) {
            if (response == 1) {
                notifyUser('Thank you, your changes have been saved');
            } else {
                notifyUser(response);
            }
            $('#saveFormLoader').hide();
            return false;
        });
    });

    $('.standard, .standardArea, #postBody').live('focus', function () {
        $(this).css('border-color', '#B1B1B1');
    });

    $('.standard, .standardArea, #postBody').live('blur', function () {
        $(this).css('border-color', '#CCCCCC');
    });

    $('.inputMechSmall').live('focus', function () {
        $(this).removeClass('inputMechSmall').addClass('inputMechSmallSelected');
    });

    $('.inputMechSmallSelected').live('blur', function () {
        $(this).removeClass('inputMechSmallSelected').addClass('inputMechSmall');
    });

    $('.inputMechSmaller').live('focus', function () {
        $(this).removeClass('inputMechSmaller').addClass('inputMechSmallerSelected');
    });

    $('.inputMechSmallerSelected').live('blur', function () {
        $(this).removeClass('inputMechSmallerSelected').addClass('inputMechSmaller');
    });

    //    $('.standard').live('focus', function () {
    //        $(this).removeClass('standard').addClass('standardSelected');
    //    });

    //    $('.standardSelected').live('blur', function () {
    //        $(this).removeClass('standardSelected').addClass('standard');
    //    });


    $('#postBody').live('focus', function () {

        $(this).css('height', '108px');
        $(this).css('width', '545px');
        //$('#StatusUpdate-form, #contextBar').css('border-color', '#5392BE');
        $('#closeCreatePost').show();
        $('#contextBar').show();
        //$('.switchOn').removeClass('switchOn').addClass('switchHighlighted');

    });

    $('.closeReplyPost').live('click', function () {

        $(this).hide();
        $(this).prev('.replyNonFocused').css('height', '28px'); //15
        $(this).prev('.replyNonFocused').css('width', '310px'); //324
        $(this).parent().css('height', '35px'); //67
        $(this).parent().parent().parent().next('div').html('');
        $(this).parent().parent().parent().next('div').next('div').next('div').html('0');
        resetAttachmentIconsToDefault();
    });

    $('#closeCreatePost').live('click', function () {
        $(this).hide();
        $('#postBody').css('height', '15px');
        $('#postBody').css('width', '415px');
        $("#postContext").val("");
        $("#chosenContext").html("All contacts");
        $('#contextBar').hide();
        $('#linkTools, #audioTools, #videoTools').hide();
        $('.addLinkToPost, .addVideoToPost, .addAudioToPost, .addImageToPost').css('background-position', '0px -60px');
        $("#postBody").val("");

        CloseAndRemoveAll();
        collapseAllAttachmentWindows();
    });

    $('.addImageToPost').live('click', function () {
        $('.addLinkToPost, .addVideoToPost, .addAudioToPost, .addImageToPost').css('background-position', '0px -60px');
        $(this).css('background-position', '0px 0px');
    });

    $('.currentChoice').live('click', function () {
        var elm = $("#audience");
        if (elm.is(":visible")) {
            elm.hide();
        } else {
            elm.show();
        }
    });

    $('.audienceChoice').live('click', function () {
        $('.currentChoice').html($(this).html());
        var id = $(this).attr("id").split('-')[1];
        $("#postContext").val(id);
        if ($(this).html() == "All contacts") {
            $("#selectedVisualDisplay").hide();
        }
        $('#audience').hide();
    });

    /*
    $('.suggestableHidden').live('focus',function(){
    $(this).parent().css('border','1px solid #666666');
    });
				
    $('.suggestableHidden').live('blur',function(){
    $(this).parent().css('border','1px solid #CCCCCC');
    });
    */

    function resetCreatePostForm() {

        $('#attachmentIds').val('');
        $('#linkUrl').val('');
        $('#videoUrl').val('');
        $('#audioUrl').val('');
        $('#hiddenLinkUrl').val('');
        $('#hiddenLinkTitle').val('');
        $('#hiddenLinkIntro').val('');
        $('#hiddenLinkThumbnail').val('');
        $('#postBody').val('');
        $('#thought').val('');
        $('#filePreview').html('');
        $('#thumbnailController').hide();
        $('#linkPreviewImage').html('');
        $('#linkPreviewTitle').html('');
        $('#linkPreviewIntro').html('');
        $('#linkPreviewUrl').html('');
        $('#videoPreviewImage').html('');
        $('#videoPreviewTitle').html('');
        $('#videoPreviewIntro').html('');
        $('#videoPreview').html('');
        $('#audioPreviewImage').html('');
        $('#audioPreviewTitle').html('');
        $('#audioPreviewIntro').html('');
        $('#audioPreview').html('');
    }

    $('#postMessage').live('click', function () {
        if ($('#postType').val() == 'Event' && !($('#createPostForm').valid())) {
            $('.cross > span > span').each(function (index) {
                var crossDiv = $(this).parent().parent();
                var tickDiv = crossDiv.next('.tick');
                crossDiv.show();
                tickDiv.hide();
                if (crossDiv.is(':hidden') && $(this).attr('htmlfor') == 'Postcode')
                    $('#addEventAddress').click();
            });

            notifyUser('Please complete marked fields.');
            return false;
        }

        /*$('#post-loader').show();*/
        $('#postMessage').fadeTo('200', 0.2);
        collapseAllAttachmentWindows();

        var serializedForm = $('#createPostForm').serialize();

        $(this).attr("disabled", "disabled");
        $.post('/Post/Create', serializedForm, function (response) {
            $('#post-loader').hide();
            if (response.indexOf('<div class="feedItem"') == -1) {
                notifyUser(response);
                $("#postMessage").removeAttr("disabled");
                return false;
            }
            response = response.split("\07\07")[1];
            var currentFeed = $('#networkActivityFeedContainer');
            resetCreatePostForm();
            if ($(".inlineFeed").size() > 0 || $(".inlineGroupFeed").size() > 0 || $(".inlineEventFeed").size() > 0) {
                currentFeed = $('#primaryFeedAlt');
                var firstFeedItem = currentFeed.find('.feedItem:first').parent();
                if (firstFeedItem.size() > 0) {
                    firstFeedItem.before(response);
                } else {
                    $('#clearBothDiv').after(response).siblings('.emptySection').remove();
                }
            }
            else {
                currentFeed.prepend(response);
            }
            $('#postMessage').fadeTo('200', 1);
            //Update NewPosts value by adding net number of new posts.
            var newCount = $('.newPosts');
            newCount.html((1 + parseInt(newCount.html())));

            newCount = $('#numberOfNetworkActivityPostsDisplayed');
            if (newCount != null)
                newCount.html((1 + parseInt(newCount.html())));

            $("#postMessage").removeAttr("disabled");
            resetShareBox();
        });

        $('#currentImage').html(1);
        $('#hiddenLinkThumbnail').val('');
        $('#totalImages').html('');
        $('#linkPreviewImage').css('margin-left', '0px');
        $('#linkPreview').hide();
        if ($('#postType').val() == 'Event') {
            $.get("/Event/InputForm", function (response) {
                //                alert(response);
                $('#Event-form').html('<ul><!--li class="formSeperator"></li-->' + response + '<!--li class="formSeperator"></li--></ul>');
                $('#StatusUpdate').trigger('click');
            });
        }

        return false;
    });

    $('#addEventSubmitButton').live('click', function () {
        if (!($('#createEventForm').valid())) {
            $('.cross > span > span').each(function (index) {
                var crossDiv = $(this).parent().parent();
                var tickDiv = crossDiv.next('.tick');
                crossDiv.show();
                tickDiv.hide();
                if (crossDiv.is(':hidden') && $(this).attr('htmlfor') == 'Postcode')
                    $('#addEventAddress').click();
            });
            notifyUser('Please complete marked fields.');
            return false;
        }

        $('#saveFormLoader').show();
        var serializedForm = $('#createEventForm').serialize();
        $.post('/Post/CreateEvent', serializedForm, function (response) {
            $('#saveFormLoader').hide();
            if (response == '0')
                notifyUser('Sorry, something went wrong when saving this event!');
            else
                document.location = '/Event/' + response;
        });
        return false;
    });

    $('#editEventSubmitButton').live('click', function () {
        if (!($('#editEventForm').valid())) {
            $('.cross > span > span').each(function (index) {
                var crossDiv = $(this).parent().parent();
                var tickDiv = crossDiv.next('.tick');
                crossDiv.show();
                tickDiv.hide();
                if (crossDiv.is(':hidden') && $(this).attr('htmlfor') == 'Postcode')
                    $('#addEventAddress').click();
            });
            notifyUser('Please complete marked fields.');
            return false;
        }

        $('#saveFormLoader').show();
        var serializedForm = $('#editEventForm').serialize();
        $.post('/Post/UpdateEvent', serializedForm, function (response) {
            $('#saveFormLoader').hide();
            notifyUser('Event details updated');
        });
        return false;
    });

    $('.cancelEventLink').live('click', function () {
        var eventIdParts = $(this).attr('id').split('-');
        $.post("/Event/Cancel", {
            id: eventIdParts[2]
        }, function (response) {
            notifyUser('This event has been cancelled and all attendees will be notified.');
            return false;
        });
    });

    $('.inviteEventLink').live('click', function () {
        $("#accordion").accordion("option", "active", 1);
    });

    $('.rescheduleEventLink').live('click', function () {
        $("#accordion").accordion("option", "active", 0);
    });

    $('.shareEventLink').live('click', function () {

        var eventIdParts = $(this).attr('id').split('-');
        $.post("/Ajax/ShareEvent", {
            eventId: eventIdParts[2]
        }, function (response) {
            notifyUser('This event has been posted to your network activity feed.');
            return false;
        });
    });

    $('#Venue').blur(function () {

        var currentValue = $('#Venue').val();

        if (currentValue != '') {

            $('.modalHeader').html('Please confirm the event location');
            var reposition = (($(window).scrollTop()) + 45);

            $('#emptyModalDialogue').css('margin-top', reposition + 'px');
            $('#emptyModalWindowBody').html('<div class="loading">&nbsp;</div>');
            $('#emptyModalDialogue').show();
            $("#emptyModalDialogue").draggable({ handle: '.modalHeader' });
            $(".closeModalDialog").hide();

            $.post("/Event/GetPlaceMatches", {
                eventLocation: $('#Venue').val()
            }, function (response) {
                $('#emptyModalWindowBody').html(response);
                return false;
            });
        }
    });

    $('#savePrimaryEmailButton').live('click', function () {

        var existingValue = $('#checkBoxDisplayValue-primary').html();
        var existingConfirmedStatus = $('#confirmedStatus-primary').html();
        var newValue = $('input:radio[name=secondaryEmailAddress]:checked').val();
        var newValueParts = $('input:radio[name=secondaryEmailAddress]:checked').attr('id').split("-");
        var newConfirmedStatus = $('#confirmedStatus-' + newValueParts[1]).html();
        if (newConfirmedStatus == "Confirmed") {
            $('#currentPrimary').html(newValue);

            $('#checkBoxDisplayValue-primary').html(newValue);
            $('#primaryEmailAddress').val(newValue);
            $('#confirmedStatus-primary').html(newConfirmedStatus);

            $('#checkBoxDisplayValue-' + newValueParts[1]).html(existingValue);
            $('#secondaryEmailAddress-' + newValueParts[1]).val(existingValue);
            $('#confirmedStatus-' + newValueParts[1]).html(existingConfirmedStatus);

            $.post("/MyKiltr/SetPrimaryEmail", {
                newPrimaryEmail: newValue
            }, function (response) {
                if (response == "1")
                    notifyUser('Thank you your primary email has been set to ' + newValue);
                else
                    notifyUser(response);
                return false;
            });
        } else {
            notifyUser('Sorry, only confirmed email addresses may be set as your primary email. Please confirm this email address by clicking \'Re-send confirmation.\'');
        }
    });


    $('li.fieldsContainer.plain #NewEmail').live('focus', function () {
        $(this).val('');
        $(this).css('color', '#000000');
    });

    $('.confirmStatus').live('click', function () {

        var newValueParts = $(this).attr('id').split("-");
        var chosenValue = $('#checkBoxDisplayValue-' + newValueParts[1]).html();

        $.post("/MyKiltr/SendEmailConfirmation", {
            email: chosenValue
        }, function (response) {
            notifyUser('We have sent an email to ' + chosenValue + ' for confirmation, please check your email.');
            $('#confirmedStatus-' + newValueParts[1]).html('Email sent');
            return false;
        });
    });

    $('#saveBasicEmailPreferencesButton').live('click', function () {
        var subscriptionString = '';
        $('.subscription:unchecked').each(function (index) {
            subscriptionString += $(this).val() + '|';
        });
        $.post("/MyKiltr/ConfirmEmailOptOuts", {
            optOuts: subscriptionString
        }, function (response) {
            notifyUser('Thank you, we have updated your email subscription list.');
        });
    });

    $('.locationMatch').live('click', function () {
        var idParts = $(this).attr('id').split('-');
        var street = $(this).find('.street').html();
        var city = $(this).find('.city').html();
        var postcode = $(this).find('.postcode').html();
        var venue = $(this).find('.pickerVenueName').text();
        $('.closeModalDialog').show();

        $('#selectedSource').val(idParts[1]);
        $('#PlaceId').val(idParts[2]);
        //alert('just populated ' + idParts[1] + '' + idParts[2]);
        $('#emptyModalDialogue').hide();
        $('#eventStreetContainer, #eventCityContainer, #eventPostcodeContainer, #eventMapContainer').show();
        $('#Venue').val(venue);
        $('#eventStreetContainer #Street').val(street);
        $('#eventCityContainer #City').val(city);
        $('#eventPostcodeContainer #Postcode').val(postcode);

        codeLength = $('#eventPostcodeContainer #Postcode').val().length;

        if (codeLength > 2) {
            var the_char = parseInt($('#eventPostcodeContainer #Postcode').val().charAt(0));
            if (is_int(the_char)) {
                /* US */
                $('#detectedLocale').html('US');
            } else {
                /* UK */
                $('#detectedLocale').html('UK');
            }

            $('#eventMapInline').slideDown(500, function () {
                mapLoad();
                $('#currentLocationFriendly').focus();
                $('#eventPostcodeContainer #Postcode').focus();
            });

        }

        if (codeLength < 2) {
            $('#eventMapInline').slideUp();
        }

        return false;
    });

    $('#venueNotListed').live('click', function () {
        $('#emptyModalDialogue').hide();
        $('#eventStreetContainer, #eventCityContainer, #eventPostcodeContainer, #eventMapContainer').show();
        $('#PlaceId').val(0);
        notifyUser('Please complete the venue address fields below.');
        $('#eventStreetContainer #Street').focus();
        $('.closeModalDialog').show();
    });

    $('#updateEvent').live('click', function () {
        $('#saveFormLoader').show();
        $.post("/Event/Save", {
            currentLocationData: $('#currentLocationHidden').val(),
            name: $('#name').val(),
            image: $('#attachmentIds').val(),
            groupType: $('#groupType').val(),
            accessType: $('#accessType').val(),
            groupSummary: $('#groupSummary').val(),
            groupDescription: $('#groupDescription').val(),
            websiteUrl: $('#websiteUrl').val()
        }, function (response) {
            if (response == 1) {
                notifyUser('Thank you, your changes have been saved');
            } else {
                notifyUser(response);
            }
            $('#saveFormLoader').hide();
            return false;
        });
    });

    $('#passwordReminderSubmit').live('click', function () {
        $.post('/Account/PasswordReminder',
            {
                emailAddress: $('#emailAddress').val()
            },
            function (response) {
                if (response == "0") {
                    notifyUser('Email address could not be found.');
                }
                else {
                    notifyUser('Temporary password has been sent.');
                }
            });
        return false;
    });

    if (urlParams['tab'] == 'team') {
        $('#company').hide();
        $('#team').show();
        $('#company-Button').removeClass('active');
        $('#team-Button').addClass('active');
        $.scrollTo('#' + urlParams['display'], 0);
    }

    if (urlParams['tab'] == 'inviteByEmail') {
        $('#importOverview').hide();
        $('#individualInvites').show();
        $('#viewImportOptions').removeClass('widgetTabLargeOn').addClass('widgetTabLargeOff');
        $('#addIndividualAddresses').removeClass('widgetTabLargeOff').addClass('widgetTabLargeOn');
    }

    if (urlParams['tab'] == 'viewnotYetInvited') {
        /*
        $('#importOverview').hide();
        $('#individualInvites').show();
        */
        $('.widgetTabLargeOn').removeClass('widgetTabLargeOn').addClass('widgetTabLargeOff');
        $('#viewnotYetInvited').removeClass('widgetTabLargeOff').addClass('widgetTabLargeOn');
        selectWidgetTab($('#viewnotYetInvited'));
    }

    /*if (urlParams['campaignId'] != null) {

    if (urlParams['action'] == '' || urlParams['action'] == null) {
    var currentAction = 'click';
    } else {
    var currentAction = urlParams['action'];
    }
    $.ajax({
    url: '/Account/CampaignProxy', //'http://kiltr.weareeveryone.com/tracker.php',
    data: "action=" + currentAction + "&campaign=" + urlParams['campaignId'],
    type: 'GET',
    async: true
    });
    }*/

    $('.badge,.badgeLast').live('mouseenter', function () {
        var idParts = $(this).attr('id').split('-');
        $('.badgeDescriptionContainer').hide();
        $('#description-' + idParts[1]).show();
    });

    $('.connectionAvatar').live('mouseenter', function () {
        $(this).css('background-position', '0px -85px');
    });

    $('.connectionAvatar').live('mouseleave', function () {
        $(this).css('background-position', '0px 0px');
    });

    $('#deleteSelectedContacts').live('click', function () {
        var recipients = $('#selectedContacts').html();
        //get the id of the selected tab then do deletes based on them
        var tabId = $('.widgetTabOn').attr('id');
        $('.cardSelected').remove();
        var uri;

        switch (tabId) {

            case 'getParticipating':
                uri = '/Group/RemoveGroupMembers';
                break;

            case 'getNotParticipating':
                uri = '/Group/DeleteDeclinedInvites';
                break;

            case 'getNotYetReplied':
                uri = '/Group/DeleteOutstandingInvites';
                break;

            case 'getRequestsToJoin':
                uri = '/Group/DeleteRequestsToJoin';
                break;

            case 'notYetInvited':
                alert('do nothing');
                return;
        }

        $.post(uri, {
            recipients: recipients,
            groupId: $('#entityId').html()
        }, function (response) {

            $('.cardPicker').html(response);
            notifyUser('success');
        });
    });

    $('#acceptSelectedRequests').live('click', function () {

        var recipients = $('#selectedContacts').html();
        $('#pickerOptions').show();

        if (recipients != 0) {
            $.post("/Group/AcceptJoinRequests", {
                recipients: recipients,
                groupId: $('#entityId').html()
            }, function (response) {
                $('.cardPicker').html(response);
                $(this).removeClass('widgetTabOff').addClass('widgetTabOn');
                $('.card').removeClass('card').addClass('cardSelected');
                notifyUser('Requests to join accepted');
            });
        } else {
            notifyUser('none selected');
        }
    });

    $('#gallery-v2-close').live('click', CloseGallery);

    function CloseGallery() {
        $('#gallery-viewer-v2-container, #smokescreen').hide();
        stopSlideShow();
        $('#gallery-viewer-v2-images').html('');
        $('#imageViewerPlayButton').attr('src', '/Images/ported/transportControls/play.gif');
        $('.playing').removeClass('playing').addClass('paused');
    }

    $('.joinGroup, .joinGroupOver').live('click', function () {

        idParts = $(this).attr('id').split("-");
        parent = $(this).parent();
        parent2 = parent.parent();
        parent2 = parent2.parent();
        nextGestureBar = parent2.next('div');
        nextGestureBar = nextGestureBar.next('div');
        nextSpan = nextGestureBar.find('.iconAction');
        groupId = idParts[1];
        postId = idParts[2];

        $.post("/Group/JoinGroupAndNotify", {
            groupId: groupId,
            postId: postId
        }, function (response) {
            if (response == 1) {
                notifyUser('Thanks, you have now joined this group!');
                parent.remove();
                if (parent2.find('.joinGroup, .joinGroupOver').length == 0) {
                    parent2.find('#groupIntroMessage').html("<a href=\"/Group/Search?searchTerms=&selectedSearchOption=groupSearch\">Find more groups</a>");
                }
            } else {
                notifyUser('You are already a member of this group!');
            }
        });


    });

    $('.gestureNonActive').live('mouseenter', function () {
        $(this).removeClass('gestureNonActive').addClass('gestureActive');
    });

    $('.gestureActive').live('mouseleave', function () {
        $(this).removeClass('gestureActive').addClass('gestureNonActive');
    });

    $('.gestureNonActive > a').live('mouseenter', function () {
        var itemParent = $(this).parent();
        itemParent.removeClass('gestureNonActive').addClass('gestureActive');
    });

    $('.gestureActive > a').live('mouseleave', function () {
        var itemParent = $(this).parent();
        itemParent.removeClass('gestureActive').addClass('gestureNonActive');
    });

    $('.gestureActiveLast').live('mouseenter', function () {
        $('.gestureBubble').css('backgroundPosition', '0px 0px');
    });

    $('.gestureActiveNormal').live('mouseenter', function () {
        $('.gestureBubble').css('backgroundPosition', '0px -77px');
    });

    $('.rsvp').live('mouseenter', function () {
        itemParent = $(this).parent();
        gestureBubbleDiv = itemParent.next('.gestureBubble');
        gestureBubbleDiv.show();
    });

    $('.gestureBubble').live('mouseleave', function () {
        $('.gestureBubble').hide();
    });

    $('.whoGestured').live('click', function () {
        $('#emptyModalWindowBody').html('<div class=\"loading\"></div>');
        var idParts = $(this).attr('id').split('-');
        $('.modalHeader').html('The following people ' + idParts[2] + ' this ' + idParts[1] + '.');
        var reposition = (($(window).scrollTop()) + 45);

        $('#emptyModalDialogue').css('margin-top', reposition + 'px');
        $('#emptyModalWindow').css('width', '605px');
        $('#emptyModalWindowOverlay').css('width', '575px');
        $('.modalHeader').css('width', '80%');
        $(".closeModalDialog").show();
        $("#emptyModalDialogue").draggable({ handle: '.modalHeader' });
        $('#emptyModalDialogue').show();
        $('.modalInstructionMessage').html('');

        $.post("/Ajax/GetPeopleWhoGestured", {
            gestureType: idParts[2],
            id: idParts[0],
            entityType: idParts[1]
        }, function (response) {
            $('#emptyModalWindowBody').html(response);
            $('.modalWindowList').css('height', '302px');
            return false;
        });
    });

    $(".addImageToPost,.addVideoToPost,.addAudioToPost,.addLinkToPost").live("mouseenter", function () {
        $(this).children("div").show();
    }).live("mouseleave", function () {
        $(this).children("div").hide();
    });



    $('.connectFromGesture').live('mouseenter', function () {
        $(this).next('.miniSpeechIcon').show();
    });

    $('.connectFromGesture').live('mouseleave', function () {
        $(this).next('.miniSpeechIcon').hide();
    });

    $('.messageFromGesture').live('mouseenter', function () {
        $(this).next('.miniSpeechIcon').show();
    });

    $('.messageFromGesture').live('mouseleave', function () {
        $(this).next('.miniSpeechIcon').hide();
    });

    $('.feelingBubble').live('mouseleave', function () {
        $('.feelingBubble').hide();
    });

    $('#welcomePost').live('mouseover', function () {

        postParent = $(this).parent();
        postParent = postParent.parent();
        postParent.css('background-color', '#FFFFFF');
    });

    /*$('#makePostPublic').live('click',function(){
		
    	
    if ($('#makePostPublic:checked').val() !== undefined) {
    $('.private').removeClass('private').addClass('public');
    }else{
    $('.public').removeClass('public').addClass('private');
    }
    });*/

    $('.attachmentListInline > li.imgHolder').live('click', function () {

        var parentDiv = $(this).parent().parent().find('.feedText>p');
        var imageDiv = $(this).parent().parent().find('.userLink').html();

        if (parentDiv.html() != null) {

            var linkDiv = $(this).parent().parent().find('.userLink').attr('href');
            var nameDiv = $(this).parent().parent().find('.feedText>.username>.userLink').html();
            var dateDiv = $(this).parent().parent().find('.feedText>.messageEnding>.relativeDate').html();

            $('.gallery-owner').html(nameDiv);
            $('.gallery-owner').attr('href', linkDiv);
            $('.gallery-date').html(dateDiv);

            $('#gallery-image-thumb').replaceWith('<a class="userLink" href="' + linkDiv + '">' + imageDiv + '</a>');
            $('#gallery-viewer-v2-foot>.userLink').replaceWith('<a class="userLink" href="' + linkDiv + '">' + imageDiv + '</a>');
            $('#gallery-description').html(parentDiv.html());
        } else {

            var inlineParentDiv = $(this).parent().parent().find('.feedReplyText>p');
            var linkDiv = $(this).parent().parent().find('.userLink').attr('href');
            var nameDiv = $(this).parent().parent().find('.feedReplyText>.username>.userLink').html();
            var dateDiv = $(this).parent().parent().find('.feedReplyText>.messageEnding>.relativeDate').html();

            $('.gallery-owner').html(nameDiv);
            $('.gallery-owner').attr('href', linkDiv);
            $('.gallery-date').html(dateDiv);

            $('#gallery-image-thumb').replaceWith('<a class="userLink" href="' + linkDiv + '">' + imageDiv + '</a>');
            $('#gallery-viewer-v2-foot>.userLink').replaceWith('<a class="userLink" href="' + linkDiv + '">' + imageDiv + '</a>');
            var userFooterLink = $('#gallery-viewer-v2-foot').find('img');
            userFooterLink.attr('width', '50');
            userFooterLink.css('margin-right', '10px');

            $('#gallery-description').html(inlineParentDiv.html());

        }

        $('#gallery-viewer-v2-container, #smokescreen').show();
        var idParts = $(this).attr('id').split('-');
        var imgDiv = $(this).find('img');
        var imgSrcThumb = imgDiv.attr('src');
        var imgSrc = imgSrcThumb.replace(/_thumb\./g, ".");

        var parentDiv = $(this).parent();
        var siblings = parentDiv.find('li > a > img');

        var img = new Image();
        var actualImageSrc = imgSrc;
        img.src = actualImageSrc;

        var imagesFound = siblings.size();

        $('#imagesFound').html(imagesFound);
        $('#currentImage').html(idParts[2]);
        $('#currentSeed').html(idParts[1]);

        var browserWidth = $(window).width();
        var browserHeight = $(window).height();

        var imgWidth = img.width;
        var imgHeight = img.height;
        var maxWidth = imgWidth / 2;
        var offset = 5;

        var wasWidth = imgWidth;
        var wasHeight = imgHeight;

        if (imgHeight > 390) {
            var imgHeight = (390);
        }

        var percentDecrease = (imgHeight / wasHeight);
        var imgWidth = Math.round((imgWidth * percentDecrease));

        var screenWidthUsed = (Math.round((1 - (imgWidth / browserWidth)) * 100) - offset);
        var marginWidth = (screenWidthUsed / 2);

        $('#emptyModalDialogue').css('margin', '45px ' + marginWidth + '%');

        var reposition = (($(window).scrollTop()) + 100);
        $('#gallery-viewer-v2').css('margin-top', reposition + 'px');
        $('#smokescreen').css('margin-top', '0px');
        $('#smokescreen').css('height', $(document).height());

        $('#gallery-viewer-v2-images').html('<img src=\'' + img.src + '\' style=\'padding: 12px 0px 0px 0px;max-height:420px;\'>');

        if (imagesFound > 1) {
            $('#imageViewerControl').show();
        } else {
            $('#imageViewerControl').hide();
        }

        return false;
    });

    $('.paused').live('click', function () {
        $('#imageViewerPlayButton').attr('src', '/Images/ported/transportControls/pause.gif');
        $(this).removeClass('paused').addClass('playing');
        startSlideShow();
    });

    $('.playing').live('click', function () {
        $('#imageViewerPlayButton').attr('src', '/Images/ported/transportControls/play.gif');
        $(this).removeClass('playing').addClass('paused');
        stopSlideShow();
    });

    $('#imageViewerFwdButton').live('click', function () {
        stopSlideShow();
        $('#imageViewerPlayButton').attr('src', '/Images/ported/transportControls/play.gif');
        $('.playing').removeClass('playing').addClass('paused');
        var maxImage = parseInt($('#imagesFound').html());
        var currentImage = parseInt($('#currentImage').html());
        var currentSeed = parseInt($('#currentSeed').html());

        if (currentImage != (maxImage)) {
            var nextImage = (parseInt(currentImage) + 1);
        } else {
            var nextImage = 1;
        }

        $('#currentImage').html(nextImage);
        currentImage = $('#emptyModalWindowBody').find('img');
        currentImage.remove();
        $('#emptyModalWindowBody').html('<img id=\'gallery-post-loader\' src=\'/Images/ported/ajax-loader-white.gif\'>');

        var nextImageId = 'img-' + currentSeed + '-' + nextImage;
        var listContainedDiv = $('#' + nextImageId);

        var idParts = listContainedDiv.attr('id').split('-');
        var nextImage = listContainedDiv.find('img');
        var nextImageSrc = nextImage.attr('src');
        var nextImageSrc = nextImageSrc.replace(/_thumb\./g, ".");

        var img = new Image();
        img.src = nextImageSrc;

        var imgWidth = img.width;
        var imgHeight = img.height;
        var maxWidth = imgWidth / 2;

        var wasWidth = imgWidth;
        var wasHeight = imgHeight;

        if (imgHeight > 390) {
            var imgHeight = (390);
        }

        var percentDecrease = (imgHeight / wasHeight);
        var imgWidth = Math.round((imgWidth * percentDecrease));

        var reposition = (($(window).scrollTop()) + 100);
        $('#gallery-viewer-v2').css('margin-top', reposition + 'px');

        var imagesFound = $('#imagesFound').html();

        $('#gallery-viewer-v2-images').html('<img src=\'' + nextImageSrc + '\' style=\'padding: 12px 0px 0px 0px;max-height:420px;\'>');
        $('#imagesFound').html(maxImage);
        $('#currentImage').html(idParts[2]);
        $('#currentSeed').html(idParts[1]);

    });

    $('#imageViewerBackButton').live('click', function () {
        stopSlideShow();
        $('#imageViewerPlayButton').attr('src', '/Images/ported/transportControls/play.gif');
        $('.playing').removeClass('playing').addClass('paused');
        var maxImage = parseInt($('#imagesFound').html());
        var currentImage = parseInt($('#currentImage').html());
        var currentSeed = parseInt($('#currentSeed').html());

        if (currentImage != 1) {
            var nextImage = (parseInt(currentImage) - 1);
        } else {
            var nextImage = maxImage;
        }

        $('#currentImage').html(nextImage);
        currentImage = $('#emptyModalWindowBody').find('img');
        currentImage.remove();
        $('#emptyModalWindowBody').html('<img id=\'gallery-post-loader\' src=\'/Images/ported/ajax-loader-white.gif\'>');

        var nextImageId = 'img-' + currentSeed + '-' + nextImage;
        var listContainedDiv = $('#' + nextImageId);

        var idParts = listContainedDiv.attr('id').split('-');
        var nextImage = listContainedDiv.find('img');
        var nextImageSrc = nextImage.attr('src');
        var nextImageSrc = nextImageSrc.replace(/_thumb\./g, ".");

        var img = new Image();
        img.src = nextImageSrc;

        var imgWidth = img.width;
        var imgHeight = img.height;
        var maxWidth = imgWidth / 2;

        var wasWidth = imgWidth;
        var wasHeight = imgHeight;

        if (imgHeight > 390) {
            var imgHeight = (390);
        }

        var percentDecrease = (imgHeight / wasHeight);
        var imgWidth = Math.round((imgWidth * percentDecrease));

        var reposition = (($(window).scrollTop()) + 100);
        $('#gallery-viewer-v2').css('margin-top', reposition + 'px');

        var imagesFound = $('#imagesFound').html();

        $('#gallery-viewer-v2-images').html('<img src=\'' + nextImageSrc + '\' style=\'padding: 12px 0px 0px 0px;max-height:420px;\'>');
        $('#imagesFound').html(maxImage);
        $('#currentImage').html(idParts[2]);
        $('#currentSeed').html(idParts[1]);

    });

    $('#messageRead').live('click', function () {

        $('.checkMessage:checked').each(function (index) {
            var idParts = $(this).attr('id').split('-');
            var parent = $(this).parent();
            var parent = parent.parent();
            $.post("/Message/MarkMessageAsRead", {
                messageId: idParts[1]
            }, function (response) {
                parent.remove();
            });
        });
    });

    $('.ui-datepicker-next,.ui-datepicker-prev').live('click', function () {

        $.post("/Event/GetEventDatesForCalendar", {
            'month': $('.ui-datepicker-month').html(),
            'year': $('.ui-datepicker-year').html(),
            'mode': $('#mode').html()
        }, function (response) {

            if (typeof (response) == 'string') {
                responseParts = response.split("|");
                $('td').each(function (index) {
                    var matchValue = jQuery.inArray($(this).text(), responseParts);
                    if (matchValue != -1) {
                        $(this).css('backgroundColor', '#5A95BF');
                    }
                });
            }
        });

        $.post("/Event/GetUserEvents", {
            'month': $('.ui-datepicker-month').html(),
            'year': $('.ui-datepicker-year').html(),
            'mode': $('#mode').html()
        }, function (response) {
            $('#eventsResults').html(response);
        });
    });

    $('#filterMyEvents').live('click', function () {
        $('#mode').html('myEvents');
        $('.filterOn').removeClass('filterOn').addClass('filterOff');
        $(this).removeClass('filterOff').addClass('filterOn');
        $.post("/Event/GetEventDatesForCalendar", {
            'month': $('.ui-datepicker-month').html(),
            'year': $('.ui-datepicker-year').html(),
            'mode': 'myEvents'
        }, function (response) {

            if (typeof (response) == 'string') {

                responseParts = response.split("|");

                $('td').each(function (index) {
                    var matchValue = jQuery.inArray($(this).text(), responseParts);
                    if (matchValue != -1) {
                        $(this).css('backgroundColor', '#5A95BF');
                    }
                });
            }
        });

        $.post("/Event/GetUserEvents", {
            'month': $('.ui-datepicker-month').html(),
            'year': $('.ui-datepicker-year').html(),
            'mode': 'myEvents'
        }, function (response) {
            $('#eventsResults').html(response);
        });
    });

    //    $('#accordion-main-whos_viewed_my_profile').live('click', function () {
    //        var target = $(this).next();
    //        if (target.find('.loading').length > 0) {
    //            $.post("/MyKiltr/WhoViewedMyProfileCount", function (response) {
    //                $('#whoHasViewedMyProfileCount').removeClass('noQtyIndicator').addClass('qtyIndicator');
    //                $('#whoHasViewedMyProfileCount').html(response);
    //            });
    //            $.post("/MyKiltr/WhoViewedMyProfile", function (response) {
    //                target.html(response);
    //            });
    //        }
    //    });

    //    $('#accordion-main-people').live('click', function () {
    //        var target = $(this).next();
    //        if (target.find('.loading').length > 0) {
    //            $.post("/MyKiltr/PeopleRecommendations", function (response) {
    //                target.html(response);
    //                $('#totalPeopleRecommendations').removeClass('noQtyIndicator').addClass('qtyIndicator');
    //                $('#totalPeopleRecommendations').html($('#peopleRecommendationsTotalCount').val());
    //            });
    //        }
    //    });

    //    $('#accordion-main-group').live('click', function () {
    //        var target = $(this).next();
    //        if (target.find('.loading').length > 0) {
    //            $.post("/MyKiltr/GroupRecommendations", function (response) {
    //                target.html(response);
    //                $('#totalGroupRecommendations').removeClass('noQtyIndicator').addClass('qtyIndicator');
    //                $('#totalGroupRecommendations').html($('#groupRecommendationsTotalCount').val());
    //            });
    //        }
    //    });

    //    $('#accordion-main-events').live('click', function () {
    //        var target = $(this).next();
    //        if (target.find('.loading').length > 0) {
    //            $.post("/MyKiltr/EventsOfInterest", function (response) {
    //                target.html(response);
    //                $('#totalEventRecommendations').removeClass('noQtyIndicator').addClass('qtyIndicator');
    //                $('#totalEventRecommendations').html($('#eventRecommendationsTotalCount').val());
    //            });
    //        }
    //    });

    $('#accordion-user-connections').live('click', function () {
        var moreButton = $(this).next().find("div:first-child.seeMoreItems");
        if (moreButton.length > 0) {
            loadMore(moreButton);
        }
    });

    $('#accordion-user-groups').live('click', function () {
        var target = $(this).next();
        var loading = target.find('.loading');
        if (loading.length > 0) {
            $.post("/People/GetUsersGroups", {
                userId: loading.next().html()
            }, function (response) {
                target.html(response);
            });
        }
    });


    $('#filterInterest').live('click', function () {
        $('#mode').html('eventsOfInterest');
        $('.filterOn').removeClass('filterOn').addClass('filterOff');
        $(this).removeClass('filterOff').addClass('filterOn');
        $.post("/Event/GetEventDatesForCalendar", {
            'month': $('.ui-datepicker-month').html(),
            'year': $('.ui-datepicker-year').html(),
            'mode': 'eventsOfInterest'
        }, function (response) {
            if (typeof (response) == 'string') {
                responseParts = response.split("|");

                $('td').each(function (index) {
                    var matchValue = jQuery.inArray($(this).text(), responseParts);
                    if (matchValue != -1) {
                        $(this).css('backgroundColor', '#5A95BF');
                    }
                });
            }
        });

        $.post("/Event/GetUserEvents", {
            'month': $('.ui-datepicker-month').html(),
            'year': $('.ui-datepicker-year').html(),
            'mode': 'eventsOfInterest'
        }, function (response) {
            $('#eventsResults').html(response);
        });
    });

    $('td').live('click', function () {
        innerLink = $(this).find('a');
        $(this).css('backgroundColor', '#000000');
        /*
        alert(innerLink.html()+' '+$('.ui-datepicker-month').html());
        */
        responseParts = $('#currentActiveDates').html().split("|");
        $('td').each(function (index) {
            var matchValue = jQuery.inArray($(this).text(), responseParts);
            if (matchValue != -1) {
                $(this).css('backgroundColor', '#5A95BF');
            }
        });

        $.post("/Event/GetUserEvents", {
            'day': $(this).text(),
            'month': $('.ui-datepicker-month').html(),
            'year': $('.ui-datepicker-year').html(),
            'mode': $('#mode').html()
        }, function (response) {
            $('#eventsResults').html(response);
        });
    });

    $('.removeAttachment_id').live('click', function () {

        var $li = $(this).parents('li');
        var $ul = $(this).parents('ul');
        var removedIndex = $ul.children().index($li);
        var currentAttachmentListDiv = $(this).parent().parent().parent().parent().parent().find('#attachmentIds');

        if (currentAttachmentListDiv.length == 0) {
            //it must be a comment attachment
            var currentAttachmentListDiv = $(this).parent().parent().parent().parent().parent().find('.attachmentIds');
        }

        var currentAttachmentList = currentAttachmentListDiv.val();
        currentAttachmentList = currentAttachmentList.substr(1, 100000);
        var attachments = currentAttachmentList.split("|");
        var i = 0;
        var newAttachmentString = '';
        for (var attachment in attachments) {
            if (attachments[attachment] != '' && i != removedIndex) {
                newAttachmentString += '|' + attachments[attachment];
            }
            i++;
        }

        currentAttachmentListDiv.val(newAttachmentString);
        $(this).parent().remove();
        return false;
    });

    $('#messageDelete').live('click', function () {

        var nullDiv = $(this).parent();
        var nullDiv = nullDiv.parent();

        i = 0;
        $('.checkMessage:checked').each(function (index) {
            i++;
            var idParts = $(this).attr('id').split('-');
            var parent = $(this).parent();
            var parent = parent.parent();
            $.post("/Message/DeleteMessage", {
                messageId: idParts[1]
            }, function (response) {
                parent.remove();

            });
        });

        var remainingMessages = $('input:checkbox');
        if ((remainingMessages.size() - i) == 0) {
            nullDiv.after('<p class=\'widgetEmptyMessage\'>You currently have no messages.</p>');
        }
    });

    $('.commentSummarizer').live('click', function () {
        $(this).find('.postRevealLoader').show();
        var loader = $(this).find('.postRevealLoader');
        var revealingMechanism = $(this);
        /*
        $(this).parent().find('.postHide').removeClass('postHide');
        */

        $(this).parent().find('.postHide').fadeIn('0', function () {
            loader.hide();
            revealingMechanism.slideUp(500);
        });

    });

    //    $('#ajax-search-results').live('mouseleave', function () {
    //        $('#ajax-search-results').hide();
    //        $('#ajax-search-results').html('');
    //    });


    $('#searchKeyword').focus(function () {
        $('#my-profile-card').hide();
        $('.my-notifications').hide();
        $('.my-meta-data-qty-surround-over').removeClass('my-meta-data-qty-surround-over');
        $('.my-avatar-over').removeClass('my-avatar-over');
        $('.hovercard').hide();
        $('#mainMediaNav').hide();
    });

    $('#searchKeyword').keyup(function () {
        //$('.ajax-search-clear').removeClass('ajax-search-clear').addClass('ajax-search-loading');
        $('.ajax-search-clear').hide();

        $('#my-profile-card').hide();
        $('.my-notifications').hide();
        $('.my-meta-data-qty-surround-over').removeClass('my-meta-data-qty-surround-over');
        $('.my-avatar-over').removeClass('my-avatar-over');
        $('.hovercard').hide();
        $('#mainMediaNav').hide();
        var charLimit = 1;
        codeLength = $('#searchKeyword').val().length;

        if (codeLength > charLimit) {
            $('.ajax-search-loading').show();
            $.post("/search", {
                keyword: $('#searchKeyword').val()
            }, function (response) {
                $('#ajax-search-results').html(response);
                $('#ajax-search-results').show();
                $('.ajax-search-loading').hide();

                if (codeLength > 0) {
                    $('.ajax-search-clear').show();
                }
                else {
                    $('.ajax-search-clear').hide();
                }
            });
        }

        if (codeLength <= charLimit) {
            $('#ajax-search-results').hide();

            if (codeLength > 0) {
                $('.ajax-search-clear').show();
            }
            else {
                $('.ajax-search-clear').hide();
            }
        }


    });





    $('.ajax-search-clear').live('click', function () {
        $('#searchKeyword').val('');
        $('#ajax-search-results').hide();
        $('#ajax-search-results').html('');
    });

    $('#inviteAllNow').live('click', function () {
        $.post("/Scripts/xhr/inviteAllNow.aspx", {

        }, function (response) {
            $('#emptyModalDialogue').hide();
            notifyUser('Thanks, your invites are now being sent.');
        });
    });


    $('.hoverCardImageContainer>img').live('mouseenter', function () {
        if ($(this).next().attr('class') == 'founder-member-hover-pic') {
            $(this).hide();
            $('.founder-member-hover-pic').show();
        }
    });

    $('.founder-member-hover-pic').live('mouseleave', function () {
        $(this).hide();
        $('.hoverCardImageContainer>img').show();
    });

    $('#founder-step2').live('click', function () {
        $('#founder-member-track').animate({
            marginLeft: '-=613px'
        }, 1000, function () {
            $.post("/Campaign/FounderMemberAccept", {
            }, function (response) {
            });

        });
    });

    $('#add-more-emails').live('click', function () {

        var emailListLength = ($('#email-input-list li').size() / 2);
        var nextIndex = (emailListLength + 1)
        var curHeight = parseInt($('#emptyModalWindow').css('height'));
        var curOuterHeight = parseInt($('#emptyModalWindowOverlay').css('height'));
        var curInnerHeight = parseInt($('#founder-member-step-2').css('height'));
        var bodyHeight = parseInt($('#emptyModalWindowBody').css('height'));

        var fmInnerHeight = parseInt($('#founder-member').css('height'));
        var increase = 60;
        $('#emptyModalWindow').css('height', (curHeight + increase) + 'px');
        $('#emptyModalWindowOverlay').css('height', (curOuterHeight + increase) + 'px');
        $('#founder-member-step-2').css('height', (curInnerHeight + increase) + 'px');

        $('#founder-member').css('height', (fmInnerHeight + increase) + 'px');
        $('#founder-member-track').css('height', (fmInnerHeight + increase) + 'px');
        $('#emptyModalWindowBody').css('height', (bodyHeight + increase) + 'px');
        $('#email-input-list').append('<li><label for="email-' + nextIndex + '">Email address</label></li><li><input type="text" class="gradient email" name="email-' + nextIndex + '" id="email-' + nextIndex + '"></li>');

        $("#email-" + nextIndex).rules("add", {
            remote: {
                url: "/Campaign/CheckEmail",
                type: "post",
                async: false
            }
        });
    });

    $('#close-modal-campaign').live('click', function () {
        $('#emptyModalDialogue').hide();
    });

    $('#invite-now').live('click', function () {
        if (!$("#founder-invite").valid()) {
            notifyUser('Please correct errors and resubmit');
            return false;
        }
        var emailListLength = ($('#email-input-list li').size() / 2);
        var emailString;
        var errorsFound = 0;
        var emailsProvided = 0;
        var emailStringValue = '';

        for (i = 1; i <= emailListLength; i++) {
            emailString = $('#email-' + i).val();
            if (emailString == '') {
                errorsFound++;
            } else {
                emailsProvided++;
            }
            emailStringValue += emailString + '|';
        }

        $("#founder-invite").validate().form()

        if (emailsProvided >= 3 && $("#founder-invite").valid()) {
            $.post("/Campaign/RegisterIgnore", {
                id: 3
            });
            $.post("/ContactImport/InviteToJoin", {
                emailString: emailStringValue,
                emailMessage: $('.founder-message').val()
            }, function (response) {
                if (response == '1') {
                    response = '';
                }
            });
            $('#founder-member-track').animate({
                marginLeft: '-=613px'
            }, 1000, function () {
                $('#emptyModalWindow').css('height', '755px');
                $('#emptyModalWindowOverlay').css('height', '725px');
                $('#founder-member').css('height', '675px');
                $('#founder-member-track').css('height', '675px');
            });
        } else {
            notifyUser('Please provide at least 3 email addresses');
        }
        return false;

    });



    $('#CreateGroupInvite').live('click', function () {
        var groupId = $('div#accordion > .inlineGroupFeed').attr('id').split('-')[1];
        var target = $(this).parent();
        $.post("/Group/CreateInviteLink/" + groupId, function (response) {
            if (response.indexOf('Copy Link') == -1) {
                notifyUser("Sorry, there was a problem creating the link.");
            }
            else {
                target.html(response);
            }
        });
        return false;
    });

    //});


    $('#partialCloseHoverCard').live('click', function () {
        $('.hovercard,.hovercardFooter').show();

        $('.hovercard').animate({
            height: '150px'
        }, 0, function () {
            $('.hovercard').show();
            $('.sharedConnectionsContainer').html('');

        });
    });

});                                                                                                                                             // end document ready

//Fix for IE9 draggable and sortable. Obtained from: http://forum.jquery.com/topic/jquery-ui-sortable-and-draggable-do-not-work-in-ie9
//It is recommended that jQuery be updated.

(function ($) { var a = $.ui.mouse.prototype._mouseMove; $.ui.mouse.prototype._mouseMove = function (b) { if ($.browser.msie && document.documentMode >= 9) { b.button = 1 }; a.apply(this, [b]); } } (jQuery));



