
$(document).ready(function() {
    pageOnLoad();

	if(document.getElementById('interests')) {
		interest_init();
	}
	
	if(document.getElementById('msgto')) {
	    ac_init();
	}
	
	if(document.getElementById('avatarSrc')) {
		avatar_init();
	}
	
	if(document.getElementById('profileEdit')) {
	    profileEdit_init();
	}
	
	if(document.getElementById('peopleTabs')) {
	    $('.whiteWindow .close').click(function(e) {
	        e.preventDefault();
	        $('#peopleTabs a').removeClass('selected');
	        $(this).parents('.body').css('display','none');
	    });
	}
	
	if(document.getElementById('memberLogin') || document.getElementById('memberLoginLeft')) {
	    if(document.getElementById('banner')) {
            banner_init();
        }
	    
	    var emailInput = document.getElementById('email');
	    if(emailInput.value != 'Email Address') {
	        emailInput.style.textAlign = 'left';
	        emailInput.style.color = "#333";
	    }
	    $('#ctl00_cphBanner_loginButton').hover(
	        function() {
	            this.src = "/webimages/memberLogin_loginHover.gif";
	        },
	        function() {
	            this.src = "/webimages/memberLogin_login.gif";
	        }
	    );
	}
	
	if(document.getElementById('peopleSearch')) {
	    new defaultKey(document.getElementById('peopleSearch'));
	}
});

function pageOnLoad() {
    if(document.getElementById('userStatus')) {
	    var textbox = new textLimit();
	    textbox.limit = 140;
	    textbox.input = document.getElementById('userStatus');
	    textbox.init();
    }


    $('#searchbuttonBasic').click(function(e) {
        e.preventDefault();
        var term = $("#searchboxBasic").val();
        //alert("term = " + term);
        if (term == "" || term == "Search") {
            alert("Please enter a name in the search box before pressing Enter or clicking Go.");
            return false;
        }
        else {
            var url = "/ok365_PeopleSearch.aspx";
            var qs = new Querystring();
            var id = qs.get("id");
            if (id && id != "") {
                url += "?id=" + id + "&term=" + term;
            }
            else {
                url += "?term=" + term;
            }
            window.location.href = url;
        }
    });
}

// Create Emoticon Array
var aEmoticons = [[':)','<img src="/WorkArea/threadeddisc/emoticons/happy.gif" />'],[':D','<img src="/WorkArea/threadeddisc/emoticons/biggrin.gif" />'],[':(','<img src="/WorkArea/threadeddisc/emoticons/sad.gif" />'],[';)','<img src="/WorkArea/threadeddisc/emoticons/wink.gif" />'],['8)','<img src="/WorkArea/threadeddisc/emoticons/cool.gif" />']];
  
function ApplyEmoticon() {
    var editor = RadEditorGlobalArray[0];
    // Assign the selection string
    var selString = editor.GetSelectionHtml().trim();

    // Find emoticon match, if found replace selection string and write to screen
    if(selString.length > 0) {
        for (i=0;i<aEmoticons.length;i++){
            if (selString == aEmoticons[i][0]){
                selString = aEmoticons[i][1];
                editor.PasteHtml(' '+selString+' ');
                break;
            }
        }
    }
    else {
        var oElem = editor.getContentElement();
        for (i=0;i<aEmoticons.length;i++){
            oElem.innerHTML = oElem.innerHTML.replace(aEmoticons[i][0],aEmoticons[i][1]);
        }
    }
 }

function showHelp(id){
    var location = "/ok365_Popup.aspx?id="+id;
    var helpWin = window.open(location,'helpWin','width=600, height=500, status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=1');
    helpWin.focus();
}

function popupForm(id){
    var location = "/ok365_Popup.aspx?ekfrm="+id;
    var popupWin = window.open(location,'helpWin','width=600, height=500, status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=1');
    popupWin.focus();
}

function popupInviteFriend(){
    var location = "/ok365_FriendInvite.aspx";
    var inviteWin = window.open(location,'inviteWin','width=500, height=400, status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=1');
    inviteWin.focus();
}

function report(postid, forumid) {
    var location = "/ok365_DiscussionBoardReportPost.aspx?post="+postid+"&forumid="+forumid;
    var reportWindow = window.open(location,'reportwin','height=600,width=600');
    reportWindow.focus();
}

function loadMainPlayer(url) {
    var targetWindow = window.open(url,'EAAAMainPlayer','scrollbars=no,resizable=no,status=no,width=990,height=600');
    targetWindow.focus();
}

function eaaNewsLink(url) {
    var eaaNewsWindow = window.open('http://150.10.32.101/' + url)
    eaaNewsWindow.focus();
}

function statuspopup(userid){
    var targetWindow = window.open('ok365_DiscussionBoardStatusPopup.aspx?user='+userid, 'Status', 'height=700, width=630, status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=1');
    targetWindow.focus();
}

function input_focus(object) {
	if(object.defaultValue == object.value) {
		object.value = "";
	}
	object.style.textAlign = "left";
}
function input_blur(object) {
	if(object.value == "") {
		object.value = object.defaultValue;
		object.style.textAlign = "center";
	}
}
function textbox_focus(object) {
	if(object.defaultValue == object.value) {
		object.value = "";
	}
	object.style.color = "#333333";
}
function textbox_blur(object) {
	if(object.value == "") {
		object.value = object.defaultValue;
		object.style.color = "#999999";
	}
}

function default_focus(object) {
	if(object.defaultValue == object.value) {
		object.value = "";
	}
}
function default_blur(object) {
	if(object.value == "") {
		object.value = object.defaultValue;
	}
}

function inputFocus(object, css, defaultValue) {
    var val;
    if(defaultValue) val = defaultValue;
    else val = object.defaultValue;
    if(val == object.value) {
        object.value = "";
    }
    if(css) renderCSS(object, css);
}
function inputBlur(object, css, defaultValue) {
    if(object.value.trim() == "") {
        var val;
        if(defaultValue) val = defaultValue;
        else val = object.defaultValue;
        object.value = val;
        if(css) renderCSS(object, css);
    }
}
function initPass(oldObject) {
	var newObject = document.createElement('input');
	newObject.type = "password";
	if(oldObject.name) newObject.name = oldObject.name;
	if(oldObject.id) newObject.id = oldObject.id;
	else newObject.id = "passwordBox";
	newObject.className = "password";
	newObject.style.color = "#333";
	oldObject.parentNode.replaceChild(newObject,oldObject);
	setTimeout("document.getElementById('"+newObject.id+"').focus();", 10);
	return newObject;
}
function renderCSS(object, css) {
    var attributes = css.split(';');
    for(var x=0;x<attributes.length;x++) {
        var elem = attributes[x].split(':');
        if(elem[0].trim() == 'text-align') {
            object.style.textAlign = elem[1].trim();
        }
        if(elem[0].trim() == 'color') {
            object.style.color = elem[1].trim();
        }
		if(elem[0].trim() == 'class') {
			object.className = elem[1].trim();
		}
    }
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function findElementPos(elemFind) {
	var elemX = 0;
	var elemY = 0;
	do {
		elemX += elemFind.offsetLeft;
		elemY += elemFind.offsetTop;
	} while ( elemFind = elemFind.offsetParent )
	return Array(elemX, elemY);
}

// Powered by EAA Tab
var powered_status = "close";
var powered_time;
var powered_height = 127;
function powered_toggle() {
	if(powered_status == "open") {
		powered_status = "closing";
		powered_time = setInterval('powered_close()', 30);
	}
	if(powered_status == "close") {
		powered_status = "opening";
		document.getElementById('powered').style.zIndex = "1000";
		powered_time = setInterval('powered_open()', 30);
	}
}
function powered_open() {
    var powered = document.getElementById('powered');
	if(powered_height > 1) {
		powered_height = powered_height - (powered_height / 8 + 1);
		powered.style.top = -powered_height+"px";
	}
	else {
		clearInterval(powered_time);
		powered_height = 0;
		powered_status = "open";
		powered.style.top = -powered_height+"px";
	}
}
function powered_close() {
    var powered = document.getElementById('powered');
	if(powered_height < 126) {
		powered_height = powered_height + ((127 - powered_height) / 8) + 1;
		powered.style.top = -powered_height+"px";
	}
	else {
		clearInterval(powered_time);
		powered_height = 127;
		powered_status = "close";
		powered.style.zIndex = "500";
		powered.style.top = -powered_height+"px";
	}
}

// Search Page
function searchTab_basic() {
    if(document.getElementById('tabBasic'))
	    document.getElementById('tabBasic').className = "selected";
	if(document.getElementById('searchBasic'))
	    document.getElementById('searchBasic').className = "show";
	if(document.getElementById('tabAdvanced'))
	    document.getElementById('tabAdvanced').className = "";
	if(document.getElementById('searchAdvanced'))
	    document.getElementById('searchAdvanced').className = "";
}
function searchTab_advanced() {
    if(document.getElementById('tabBasic'))
	    document.getElementById('tabBasic').className = "";
	if(document.getElementById('searchBasic'))
	    document.getElementById('searchBasic').className = "";
	if(document.getElementById('tabAdvanced'))
	    document.getElementById('tabAdvanced').className = "selected";
	if(document.getElementById('searchAdvanced'))
	    document.getElementById('searchAdvanced').className = "show";
}

// Event Search
eventSearch_current = "Distance";
function eventSearch_select(name) {
	document.getElementById('eventSearchTab'+eventSearch_current).className = "";
	document.getElementById('eventSearchForm'+eventSearch_current).className = "hide";
	
	document.getElementById('eventSearchTab'+name).className = "selected";
	document.getElementById('eventSearchForm'+name).className = "";
	eventSearch_current = name;
	return false;
}

function profileLabel_toggle(name) {
	var label = document.getElementById(name);
	if(label.className == 'label') {
		label.className = 'labelOpen';
	}
	else {
		label.className = 'label';
	}
}

var banner = { current:1, time:null };
function banner_init() {
    $('#banner .display').hover(
        function() {
            clearTimeout(banner.time);
        },
        function() {
	        banner.time = setTimeout('banner_next()', 5000);
        }
    );
    banner.time = setTimeout('banner_next()', 5000);
}
function banner_next() {
	document.getElementById('display_'+banner.current).className = "hide";
	document.getElementById('menu_'+banner.current).className = "itemDe";
    banner.current++;
    if(banner.current > 4) {
        banner.current = 1;
    }
	document.getElementById('display_'+banner.current).className = "";
	document.getElementById('menu_'+banner.current).className = "item";
	banner.time = setTimeout('banner_next()', 5000);
}
function banner_show(num) {
    clearTimeout(banner.time);
	document.getElementById('display_'+banner.current).className = "hide";
	document.getElementById('menu_'+banner.current).className = "itemDe";
	document.getElementById('display_'+num).className = "";
	document.getElementById('menu_'+num).className = "item";
	banner.current = num;
}
function banner_rotate() {
    clearTimeout(banner.time);
	banner.time = setTimeout('banner_next()', 5000);
}

// Messaging Control
function msg_checkAll(master){
   var checked = master.checked;
   var col = document.getElementsByTagName('INPUT');
   for (var i=0; i < col.length; i++) {
       if (col[i].id.indexOf('forum_message_delcheck') == 0) { 
           col[i].checked = checked;
       }
   }
}
function msg_validatechk(folder){
    var params = "&folder=0";
    if(folder == 'sent') {
        params = '&folder=1';
    }
	var x = "";
	var col = document.getElementsByTagName('INPUT');
	for (var i=0; i < col.length; i++) {
		if (col[i].id.indexOf('forum_message_delcheck') == 0) { 
			if (col[i].checked == true){
			    if(x.length > 0) {
			        x += ',';
			    }
				x += col[i].value;
			}
		}
	}
	if(x.length == 0){
		alert('No messages selected');
	}
	else {
	    if(confirm('Delete all selected messages?')== true) {
	            window.location.href = '/ok365_MessagingDelete.ashx?id='+x+params;
	    }
	}
}

// Interests Slide Nobs
var interest_mouseX;
var interest_left = 0;
var interest_startX = 0;
var interest_current = 0;
var interest_time;
var interest_mouseDown = false;
function interest_init() {
	var interests = document.getElementById('interests');
	interests.onmousemove = interest_findMousePos;
	document.onmouseup = interest_quit;
	interests.onselectstart = cancelSelect;
	
	var sliders = interests.getElementsByTagName('tr').length;
	for(var x=0;x<sliders;x++) {
		var rating = document.getElementById('interest_tb_'+(x+1)).value;
		document.getElementById('interest_nb_'+(x+1)).style.left = rating * 30 + "px";
	}
}
function interest_reset() {
	var sliders = document.getElementById('interests').getElementsByTagName('tr').length;
	for(var x=0;x<sliders;x++) {
		document.getElementById('interest_tb_'+(x+1)).value = '1';
		document.getElementById('interest_nb_'+(x+1)).style.left = "30px";
	}
}
cancelSelect = function() {
	if(interest_mouseDown)
		return false;
}
function interest_findMousePos(e) {
	if(!e) e = window.event;
	interest_mouseX = e.clientX;
}
function interest_quit() {
	clearTimeout(interest_time);
	if(interest_mouseDown == true) {
		document.getElementById('interest_tb_'+interest_current).focus();
		interest_mouseDown = false;
	}
}
function interest_drag(num) {
	clearTimeout(interest_time);
	interest_current = num;
	interest_mouseDown = true;
	interest_left = document.getElementById('interest_tb_'+num).value * 30;
	interest_startX = interest_mouseX;
	interest_time = setTimeout('interest_follow()', 30);
}
function interest_jump(object,num) {
	interest_current = num;
	var pos = findElementPos(object);
	var newLeft = interest_mouseX - pos[0];
	interest_set(newLeft);
}
function interest_follow() {
	var newLeft = interest_left + (interest_mouseX - interest_startX);
	if(newLeft > 150)
		newLeft = 150;
	if(newLeft < 0)
		newLeft = 0;
	interest_set(newLeft);
	if(interest_mouseDown)
	{
		interest_time = setTimeout('interest_follow()', 30);
	}
}
function interest_set(left) {
	var rating = Math.round((left - 7) / 30);
	document.getElementById('interest_nb_'+interest_current).style.left = rating * 30 + "px";
	document.getElementById('interest_tb_'+interest_current).value = rating;
}
function interest_valueChange(e,num) {
	var key, value;
	if(window.event) {
		var event = window.event;
		key = event.keyCode;
	}
	else {
		key = e.which;
	}
	switch(key)
	{
		case 48:
			interest_update(num,'0');
			return false;
		case 49:
			interest_update(num,'1');
			return false;
		case 50:
			interest_update(num,'2');
			return false;
		case 51:
			interest_update(num,'3');
			return false;
		case 52:
			interest_update(num,'4');
			return false;
		case 53:
			interest_update(num,'5');
			return false;
		case 8:
			return true;
		case 9:
			return true;
		case 37:
			return true;
		case 39:
			return true;
		case 46:
			return true;
		default:
			return false;
	}
}
function interest_update(num,value) {
		document.getElementById('interest_nb_'+num).style.left = value * 30 + "px";
		document.getElementById('interest_tb_'+num).value = value;
}

function submitMessage(subject,control) {
    var returned = CommunityMsgClass.GetObject(control).SendMessage('Please choose at least one recipient.');
    
    if(returned) {
        subject.value = StripHtml(subject.value);
        subject.value = subject.value.replace('&#','');
        document.getElementById('msgto').value = "";
    
        if(subject.value.length < 1 || subject.value == "Subject:") {
            subject.value = "(no subject)";
        }
    }
    
    return returned;
}

function ac_init() {
    $("#msgto").autocomplete('/ok365_MessagingRecipients.ashx', {
		minChars: 2,
		multiple: false,
		matchContains: true,
		mustMatch: false,
		autoFill: false,
		formatItem: function(row) {
			return row[0];
		},
		formatMatch: function(row) {
		    return row[0];
		},
		formatResult: function(row) {
			return row[0];
		}
    }).result(function(event, data, formatted) {
        $(this).val("");
        $("#autocomplete").append("<span onclick=\"ac_focus()\" class=\"tinyButton\"><span>" + data[0] + " <span class=\"close\" onclick=\"ac_remove(this)\" title=\"Remove this recipient\">" + data[1] + "</span></span></span>");
    });    
    $("#msgto").focus(function() {
        inputFocus(this,'','To:');
    });
	$("#msgto").blur(function() {
	    ac_update();
		inputBlur(this,'','To:');
	});
}
function ac_focus() {
    $("#msgto").focus();
}
function ac_remove(object) {
    $(object).parent().parent().remove();
	ac_update();
}
function ac_update() {
		var ads = document.getElementById('autocomplete').getElementsByTagName('span');
		var ids = "";
		for(var x=0;x<ads.length;x++) {
		    if(ads[x].className == "close") {
		        if(ids.indexOf(ads[x].innerHTML + ",") != 0 && ids.indexOf("," + ads[x].innerHTML + ",") < 0) {
		            ids += ads[x].innerHTML + ",";
		        }
		    }
		}
		ids = ids.substring(0,ids.length-1);
		//alert(ids);
		$("#ektouseridctl00_ContentPlaceHolder1_MessagingControl").val(ids);
}


function avatar_init() {
	
	$('#standardAvatars li').add('#uploadedAvatars li').click(function() {
		$('#standardAvatars li').add('#uploadedAvatars li').removeClass('selected');
		$(this).addClass('selected');
		$('#standardAvatar').html($(this).html());
	});
	
	$('#selectStandard').click(function() {
		var standard;
		if(standard = $('#standardAvatar').children('img')[0]) {
			$('#avatarSrc').val(standard.src);
			$('#currentAvatar').html(standard);
			$('#avatarFilename').val('');
			$('#standardAvatars li').add('#uploadedAvatars li').removeClass('selected');
		}
		else {
			alert('No avatar selected');
		}
	});
	
	if (document.getElementById('selectAvatarDisplay') != null) {
	    if($('#selectAvatarDisplay').val() == "standard") {
		    $('#uploadedAvatars').addClass('hide');
		    $('#standardAvatars').removeClass('hide');
	    }
	    else {
		    $('#standardAvatars').addClass('hide');
		    $('#uploadedAvatars').removeClass('hide');
	    }
	    $('#selectAvatarDisplay').change(function() {
		    if($(this).val() == "standard") {
			    $('#uploadedAvatars').addClass('hide');
			    $('#standardAvatars').removeClass('hide');
		    }
		    else {
			    $('#standardAvatars').addClass('hide');
			    $('#uploadedAvatars').removeClass('hide');
		    }
	    });
	}
	
	new Ajax_upload('#browseAvatar', {
		action: '/AvatarHandler.ashx',
		name: 'avatar',
		onSubmit : function(file , extension){
			if (! (extension && /^(jpg|png|jpeg|gif)$/.test(extension))){
				// extension is not allowed
				alert('Error: invalid file extension');
				// cancel upload
				return false;
			}
			else {
                var image = '<img src="/webimages/avatarLoading.gif" alt="Loading" />';
                $('#currentAvatar').html(image);
            }
		},
		onComplete : function(file , response){
			//jQuery.each(jQuery.browser, function(i, val) {
			//	if(i=="mozilla" && jQuery.browser.version.substr(0,3)=="1.9")
			//		gBrowser.selectedBrowser.markupDocumentViewer.fullZoom = 1;
			//});
			if(response.indexOf("/") == 0) {
                $('#avatarFilename').val(file);
                var image = '<img src="'+response+'" alt="'+response+'" />';
                $('#currentAvatar').html(image);
                $('#avatarSrc').val(response);
                $('#uploadedAvatars').append('<li>'+image+'</li>');
                $('#uploadedAvatars li:last-child').click(function() {
	                $('#standardAvatars li').add('#uploadedAvatars li').removeClass('selected');
	                $(this).addClass('selected');
	                $('#standardAvatar').html($(this).html());
                });
            }
            else {
		        alert(response);
                var image = $('#avatarSrc').val();
                image = '<img src="'+image+'" alt="'+image+'" />';
                $('#currentAvatar').html(image);
		    }
		}	
	});
}
function avatar_upload(src, filename) {

}

function profileEdit_init() {
    $('#phpTabs a').click(function() {
        var count = 0;
        var inputs = document.getElementById('profileEdit').getElementsByTagName('input');
        if(inputs.length > 0) {
            for(var x=0;x<inputs.length;x++) {
                if((inputs[x].type == "text" || inputs[x].type == "password")&& inputs[x].defaultValue != inputs[x].value) {
                    count++;
                }
                if(inputs[x].type == "checkbox" && inputs[x].defaultChecked != inputs[x].checked) {
                    count++;
                }
            }
        }
        var selects = document.getElementById('profileEdit').getElementsByTagName('select');
        if(selects.length > 0) {
            for(var y=0;y<selects.length;y++) {
                if(!selects[y].options[selects[y].selectedIndex].defaultSelected && selects[y].id != 'selectAvatarDisplay') {
                    count++;
                }
            }
        }
        var textareas = document.getElementById('profileEdit').getElementsByTagName('textarea');
        if(textareas.length > 0) {
            for(var z=0;z<textareas.length;z++) {
                if(textareas[z].defaultValue != textareas[z].value) {
                    count++;
                }
            }
        }
        if(document.getElementById('avatarSrc') && document.getElementById('avatarSrc').value != document.getElementById('avatarDefaultSrc').value) {
            count++;
        }
        if(count > 0) {
            if(confirm("Lose unsaved changes?")){
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return true;
        }
    });
}

// Submit on Enter Key
// onkeypress="return enterKey(event,'objectID')"
function enterKey(e,id) {
	if(document.getElementById(id)) {
		if(!e) e = window.event;
		var key = e.which;
		if(!key) key = e.keyCode;
		if (key && key == 13) {
			//eval(code);
			var object = document.getElementById(id);
			if(object.tagName == 'A') {
				var href = object.href.replace(window.location,"");
				if(href.length > 1) {
					eval(unescape(object.href.replace(/^javascript:/i,"")));
				}
				else {
					object.onclick();
				}
				return false;
			}
			else if(object.tagName == 'INPUT' || object.tagName == 'BUTTON') {
			    object.click();
				return false;
			}
		}
	}
	return true;
}

function defaultKey(frame) {
	var self = this;
	this.frame = frame;
	this.button = $(this.frame).find('input.defaultButton,button.defaultButton,a.defaultButton')[0].id;
	if(this.frame && this.button.length > 0) {
		$(this.frame).find('input:text,input:password,input:radio,input:checkbox').keypress(function(e) {
			return enterKey(e, self.button);
		});
	}
}

var submitTimes = 0;
function submitOnce() {
    submitTimes++;
    if(submitTimes < 2) {
        return true;
    }
    else {
        return false;
    }
}

/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008
	
	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}

/* End of Querystring block */

function selects_hide() {
	if($.browser.msie && parseInt($.browser.version,10) < 7) {
		$('select').css('visibility','hidden');
	}
}
function selects_show() {
	if($.browser.msie && parseInt($.browser.version,10) < 7) {
		$('select').css('visibility','visible');
	}
}
function addFriend_open(id) {
	selects_hide();
	$('#overlay').css('display','block');
	$('#addFriend').css('display','block');
	addFriend_loadControl(id);
}
function addFriend_close() {
	selects_show();
	$('#overlay').css('display','none');
	$('#addFriend').css('display','none');
	$('#addFriend').html('');
}
function addFriend_reset() {
	var textarea = $('#addFriend textarea.message')[0];
	textarea.value = "";
	textarea.focus();
	textarea.blur();
}

function peopleList_open(statusID) {
	selects_hide();
	$('#overlay').css('display','block');
	$('#peopleList').css('display','block');
	peopleList_LoadUserStatusLikes(statusID);
}
function peopleList_close() {
	selects_show();
	$('#overlay').css('display','none');
	$('#peopleList').css('display','none');
	$('#peopleListBody').html('');
}

function reloadFriendsInCommon() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_People.asmx/ReloadFriendsInCommonList",
        data: "{}",
        dataType: "json",
        success: function(result, textStatus) {
            $("#FriendsInCommon_List").html(result);
        },
        error: function(request, status, err) {
            alert("error:" + status + "/" + err);
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
        }
    });
}

function receiveUpdates_toggle(object,userid) {
    object.className = "loading";
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_People.asmx/UpdateReceive",
        data: "{'userID':'" + userid + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            if(result == true) {
                object.className = "checked";
            }
            else {
                object.className = "";
            }
        },
        error: function(request, status, err) {
            alert("error:  " + status + "\r\n\r\n" + err);
        }
    });
    return false;
}


function textLimit() {
	this.limit = 200;
	this.regex = /<[^ ]\/?[^>]+>/gi;
	this.allowOver = false;
	this.input = null;
	this.count = null;
	this.remaining = null;
	this.init = function() {
		var self = this;
		this.input.onkeydown = function(event) {
			if(this.value.length >= self.limit) {
				var e = event;
				if(!e) e = window.event;
				if(!e.which) e.which = e.keyCode;
				if(e.which > 46 || e.which == 13 || e.which == 32) {
					return false;
				}
			}
		}
		this.input.onkeyup = function() {
			var val = self.clean(this.value);
			if(!self.allowOver && val.length > self.limit) {
				val = val.substr(0, self.limit);
			}
			if(this.value != val) {
				this.value = val;
				self.input.scrollTop = self.input.scrollHeight;
			}
			self.setCount(val.length);
			self.setRemaining(val.length);
		};
		this.setCount(this.input.value.length);
		this.setRemaining(this.input.value.length);
	}
	this.setCount = function(length) {
		if(this.count) {
			this.count.innerHTML = length;
			this.adjustStyle(this.count, length);
		}
	}
	this.setRemaining = function(length) {
		if(this.remaining) {
			this.remaining.innerHTML = this.limit - length;
			this.adjustStyle(this.remaining, length);
		}
	}
	this.adjustStyle = function(object, length) {
		if(length > this.limit) {
			// uncomment if jQuery
			$(object).addClass('error');
			//object.className = "error";
		}
		else {
			// uncomment if jQuery
			$(object).removeClass('error');
			//object.className = "";
		}
	};
	this.clean = function(value) {
		return value.replace(this.regex, '');
	}
}

function toggleCommentsArea(statusID) {
    $("#statusComments_" + statusID).toggleClass("hide");
}

function commentBox_showAll(object) {
    var ul = $(object).next('ul');
    if(ul.hasClass('showComments')) {
        object.innerHTML = "Show all " + $(ul).find('li').length + " comments...";
        object.title = object.innerHTML;
	    ul.removeClass('showComments');
	}
	else {
	    object.innerHTML = "Hide comments...";
	    object.title = object.innerHTML;
	    ul.addClass('showComments');
	}
	return false;
}

function postComment(statusID) {
    var inputBox = document.getElementById("comment_" + statusID);
    var comment = inputBox.value;
    if (comment == "Add a comment..." || comment == "") {
        return;
    }
    var tempComment = "<li><div class='image'><img src='/webimages/status_comment_ajax-loader.gif' alt='' /></div>" +
                      "<div class='info'><div class='name'>&nbsp;</div><p>Loading...</p></div></li>";
    $("#statusComments_" + statusID).find("ul").append(tempComment);
    inputBox.value = "";
    inputBox.focus();
    inputBox.blur();
    comment = comment.replace(/'/g, "&#39;");
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_People.asmx/PostStatusComment",
        data: "{'statusID':'" + statusID + "','comment':'" + comment + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            if (result.ok) {
                $("#statusComments_" + result.statusID).replaceWith(result.statusHtml);
            }
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
        }
    });
}

function loadFriendIndex(userID, letter, page) {
    $("#friendLoadingMessage").css("display","block");
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_People.asmx/LoadFriendIndex",
        data: "{'userID':'" + userID + "','letter':'" + letter + "','pageNum':'" + page + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            $("#FriendListContent").html(result);
            $("#friendLoadingMessage").css("display","none");
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
            $("#friendLoadingMessage").css("display","none");
        }
    });
}

function loadAllFriends(userID, page) {
    $("#friendLoadingMessage").css("display","block");
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_People.asmx/LoadAllFriends",
        data: "{'userID':'" + userID + "','pageNum':'" + page + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            $("#FriendListContent").html(result);
            $("#friendLoadingMessage").css("display","none");
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
            $("#friendLoadingMessage").css("display","none");
        }
    });
}

function loadFriendsStatusUpdates(userID, page) {
    $("#friendLoadingMessage").css("display","inline");
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_People.asmx/LoadFriendsStatusUpdates",
        data: "{'userID':'" + userID + "','pageNum':'" + page + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            $("#FriendListContent").html(result);
            $("#friendLoadingMessage").css("display","none");
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
            $("#friendLoadingMessage").css("display","none");
        }
    });
}

function deleteStatusComment(commentID) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_People.asmx/DeleteStatusComment",
        data: "{'commentID':'" + commentID + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            $("#jsStatusCommentID_" + commentID).remove();
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
        }
    });
}

function toggleLike_UserStatus(statusID, e) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_Likes.asmx/ToggleLike_UserStatus",
        data: "{'statusID':'" + statusID + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            if (result.likeStatus == 1) {
                var num = parseInt(e.innerHTML,10) + 1;
                e.innerHTML = String(num);
                e.title = "Unlike";
                e.setAttribute("class", "unlike");
            }
            else {
                var num = parseInt(e.innerHTML,10) - 1;
                e.innerHTML = String(num);
                e.title = "Like";
                e.setAttribute("class", "like");
            }
            if (result.likeStatus == 0 || result.likeStatus == 1) {
                var infoDiv = $(e).parents("div.info");
                var showLikesDiv = infoDiv.find("div.showLikes");
                if (showLikesDiv && showLikesDiv.length > 0) {
                    showLikesDiv.replaceWith(result.teaserHtml);
                }
                else {
                    infoDiv.append(result.teaserHtml);
                }
            }
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
        },
				complete: function (XMLHttpRequest, textStatus) {
						if(typeof SetLinksToOpener == 'function'){
							SetLinksToOpener();
						}
        }
    });
}

function deleteUserStatus(statusID, e) {
    var ok = confirm("Are you sure you want to remove this status and all associated comments/likes?  This action cannot be undone.");
    if (!ok) {
        return;
    }
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_People.asmx/DeleteUserStatus",
        data: "{'statusID':'" + statusID + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            if (result.ok) {
                var li = $(e).parents("li");
                li.remove();
            }
            else {
                alert("Unable to remove status at this time.");
            }
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
        }
    });
}

function peopleList_LoadUserStatusLikes(statusID) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ok365_Likes.asmx/GetAllLikesOfStatus",
        data: "{'statusID':'" + statusID + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            document.getElementById('peopleListBody').innerHTML = result.detailHtml;
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
        },
				complete: function (XMLHttpRequest, textStatus) {
						if(typeof SetLinksToOpener == 'function'){
							SetLinksToOpener();
						}
        }
    });
}

function RememberMe_Set(a,b) {
    var url = "/ok365_RememberMeCookie.ashx?a="+a+"&b="+b;
  RememberMeRequest("http://" + location.host + url);
  //RememberMeRequest("http://www.oshkosh365.com" + url);
}

function RememberMe_UnSet() {
    var url = "/ok365_RememberMeCookie.ashx?c=1";
  RememberMeRequest("http://" + location.host + url);
  //RememberMeRequest("http://www.oshkosh365.com" + url);
}

function RememberMeRequest(url) {
    $.ajax({
	async: false,
        type: "GET",
        url: url,
        data: "",
        dataType: "text",
        success: function(result, textStatus) {
            ;
        },
        error: function(request, status, err) {
            ;
        }
    });
}

function UserImages_List(userID,page) {
    suspendDeletes();
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/RenderUserImageList.asmx/RenderAllUserImages",
        data: "{'userID':'" + userID + "','page':'" + page + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            $("#ulUserImages").html(result);
            $("#ulUserImages li").click(function() {
                $("#ulUserImages li").removeClass("selected");
                $(this).addClass("selected");
            });
            hideDeletes();
            readyDeletes(false);
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
        }
    });
}

function readyDeletes(first) {
    $("#ulUserImages li").each(function() {
        if (first) {
            $(this).find(".delete").toggleClass("hide", true);
        }
        $(this).mouseenter(function() {
            $(this).find(".delete").toggleClass("hide", false);
        }).mouseleave(function() {
            $(this).find(".delete").toggleClass("hide", true);
        });
    });
}

function hideDeletes() {
    $("#ulUserImages li .delete").toggleClass("hide", true);
}

function suspendDeletes() {
    $("#ulUserImages li").each(function() {
        $(this).unbind("mouseenter");
        $(this).unbind("mouseleave");
    });
}

function UserImage_delete(photoID) {
    suspendDeletes();
    var ok = confirm("Are you sure you want to delete this image from the server?\nThis action cannot be undone.");
    readyDeletes(false);
    hideDeletes();
    if (!ok) {
        return;
    }
    $("#userimagelistli_" + photoID).html("<img src=\"/webimages/friendloader.gif\" alt=\"Deleting...\" />");
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/RenderUserImageList.asmx/DeleteUserImage",
        data: "{'photoID':'" + photoID + "'}",
        dataType: "json",
        success: function(result, textStatus) {
            $("#userimagelistli_" + photoID).remove();
        },
        error: function(request, status, err) {
            $("#userimagelistli_" + photoID).remove();
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
        }
    });
}

function UserImage_GetUserID() {
    var UserID = "0";
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/RenderUserImageList.asmx/GetLoggedInUser",
        data: "{}",
        dataType: "json",
        success: function(result, textStatus) {
            UserID = result;
        },
        error: function(request, status, err) {
            if (request.readyState == 4) {
                switch (request.status) {
                // Page-not-found error
                case 404:
                    alert('Error: Not Found. The requested URL could not be found.');
                    break;
                // Internal server error
                case 500:
                    alert(request.responseText);
                    break;
                default:
                    break;
                }
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
        }
    });
    return UserID;
}

function randomInt(min, max) {
    return Math.floor(Math.random()*(max+1-min)) + min;
}

function checkLength(textareaid, max, outputid) {
    var text = $("#" + textareaid).val();
    var textlength = text.length;
    if (textlength > max) {
        $("#" + textareaid).val(text.substr(0,max));
        $("#" + outputid).html('You have reached the max.');
    }
    else {
        if ((max - textlength) == 1) {
            $("#" + outputid).html('(' + (max - textlength) + ' character left)');
        }
        else {
            $("#" + outputid).html('(' + (max - textlength) + ' characters left)');
        }
    }
}