/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function(){		
		
	if(typeof dvl_onready_first == 'function') dvl_onready_first(); 
		
	var response_window;
		
	var http = ('https:' == document.location.protocol) ? 'https://' : 'http://'; // jwg 2010-08-02 
	
	/*	
	if ($("#notice_action-attach_request")) { // jwg 2009-11-16 -- an onClick that works with IE, Safari and Chrome ...
		
		$("#notice_action-attach_request").css("cursor", "pointer").click(function() { 
				if ($("#notice_action-attach_browse").hasClass('display_none')) {
					$("#notice_action-attach_browse").removeClass('display_none');
					$("#notice_action-attach_browse").addClass('display_block');
					$("#notice_action-attach_request").removeClass('attach_open');
					$("#notice_action-attach_request").addClass('attach_close');
					$("#notice_action-attach_request").blur();
				} else {
					$("#notice_action-attach_browse").removeClass('display_block');
					$("#notice_action-attach_browse").addClass('display_none');
					$("#notice_action-attach_request").removeClass('attach_close');
					$("#notice_action-attach_request").addClass('attach_open');
					
					if ($('#show_post_form').length) {
						hideDiv('form_notice');
						hideDiv('list_shim');
						showDiv('list_shimx');
					}		
					
					$("#notice_action-attach_request").blur();
				}
		});
	}
	*/
	
	// jwg 2010-04-13 -- close any open user action menu when user clicks anywhere inside wrap area
	$('#wrap').click(function(){ 
			close_action_menus();
		});	
	
	/* 
	if ($("#notice_action-recipient_request")) { 
		$("#notice_action-recipient_request").css("cursor", "pointer").click(function() { 
			var uid = $("#recipient_request_user").val();
			$("#notice_action-recipient_request").blur();
			showAddrLists(uid); // * means 'for logged in user'
		});
	}
	*/
	
	if ($('div.expandable p')) {
	  // override some default options
	  $('div.expandable').expander({
	    slicePoint:       300,  // default is 100 -- 2010-05-07 changed 500 to 150
	    window:					  15		// default is 4 (number of words that must remain else don't bother)
	    //expandText:         '[...]', // default is 'read more...'
	    //collapseTimer:    5000, // re-collapses after 5 seconds; default is 0, so no re-collapsing
	    //userCollapseText: '[^]'  // default is '[collapse expanded text]'
	  });
	}
	
	/* jwg -- alternate approach to hoverIntent */
	if ($("#form_notice #notice_data-text")) {
		//$( "#form_notice #notice_data-text" ).autogrow();
	  $( "#form_notice #notice_data-text" ).autogrow({'maxHeight':'200'}); // jwg 2010-08-28
	  $( '.toptext.notext' ).css({'display':'none'});
	  $( '.toptext.hastext' ).css({'display':'inline-block'});
		$( 'div#keywords_area').css({display:'block'}); 
		$( '#form_notice #notice_attach_tab, .form_note #notice_text-countused' ).fadeIn(650);
	}

	$( '.postto_network' ).each(function(){
		$( this ).click(function(){

			var thisClass = $( this ).attr('class');
			if (thisClass.indexOf('not_connected') > -1) { // jwg 2010-07-05 - never allow not-yet-connected icons to be actually selected
				var theid = $( this ).attr('rel');
				if (isNaN(theid)) {
					alert("Unexpected id in postto icon: "+theid);
					return;
				}
        var service_name = null;
        var settings_path = null;
        switch (theid) { 									// open document files and photoshop files and image files directly
        	case '1':	
						service_name = 'Twitter';
						settings_path = 'settings/twitter';
						break;
        	case '2':	
						service_name = 'Facebook';
						settings_path = 'fb.php';	// special case determined by current router mapping
						break;
        	case '4':	
						service_name = 'Blogspot';
						settings_path = 'settings/blogger';
						break;
        	case '6':	
						service_name = 'Wordpress';
						settings_path = 'settings/wp';
						break;
				}
				if (service_name == null) {
					alert("Service connection unknown.");
					return;
				}
				if (confirm('You have not yet connected to '+service_name+'.\n\nWould you like to setup a '+service_name+' connection?')) {
						
						document.location.href = http + getCurrentDomain()+'/'+settings_path;
						return;
				} 
				
			} else {				

				var isChecked = false; // jwg 2010-05-05
				if( thisClass.indexOf( 'selected' ) > -1 ) {
					$( this ).removeClass( 'selected' );
					isChecked = false;
				} else {
					$( this ).addClass( 'selected' );
					isChecked = true; // jwg 2010-05-05
				}
			} 
	
			$('#postto_'+$(this).attr('rel')).attr('checked', isChecked); // jwg 2010-05-05
		});
	});
	
	$( '#form_notice #notice_attach_tab .icons .icon' ).each(function(){
		$( this ).click(function(){
			var thisClass	= $( this ).attr('class' );

				if( thisClass.indexOf( 'selected' ) > -1 ){
					$( this ).removeClass( 'selected' );
					// jwg 2010-08-30 - done in nother fct
					//if ($(this).hasClass('private')) {	// jwg 2010-05-05
					//	document.getElementById('notice_private').checked = false;
					//}
				} else {
					$( this ).addClass( 'selected' );
					//if ($(this).hasClass('private')) {	// jwg 2010-05-05
					//	document.getElementById('notice_private').checked = true;
					//}
				}
		});
	});
	
	
	// 2010.05.04 KJD: Do the hover over
	$( '#entity_user div.image, #entity_user div.avatar, #entity_user a.profile_nickname, span.author a.url, .photo' ).each(function(e){
		$( this )
			.hoverIntent({
				interval: 500,
				over: function(e) {
					var token 		= $("input#token").val();
					if (token) { // jwg 2010-05-31
						// 2010.05.04 KJD: Get the profile id
						var thisImage	= $( this ).parents('.vcard.author').find('img' );
						if (thisImage && $(thisImage).attr('src')) { // jwg 2010-06-10
							var profile_id	= ( $( thisImage ).attr('rel') )?$( thisImage ).attr('rel'):$( thisImage ).attr( 'src' ).split('/').pop().split('-')[0];
							if (profile_id == 'default') return; // jwg 2010-06-15
							var requesturl 	= getBasePath() + "/getuserinfo/"+ profile_id +"/?token="+token;
						} else {
							return;
						}
					} else {
						return;
					}
				$.ajax({ 
					url: requesturl, 
					type: 'get', 
					success: function( data ){
						if (data) { // jwg 2010-05-05 -- do not display if no response
							$( 'body' )
								.append( "<div class='profilepopup'>" + data + "</div>" );
						
							$( 'div.profilepopup' )
								.css({'left': e.pageX-50, 'top': e.pageY-50 })
								.fadeIn(500)
								.hoverIntent({
									timeout: 50,
									over: function(){},
									out: function() {
										$( this ).fadeOut(500,function(){$( this ).remove()});
									}
								});
						}
					}});
				},
				out:function(){}
			});
	});
		
	// jwg 2010-06-06
	if ($("#notice_data-tags")) {
		resetTagHint();
	}

	$( '#notice_data-tags' ).each(function(){
		$( this )
			.focus(function(){
				var hint = 'keywords:';
				var thisHTML	= $( this ).val();
				
				$( this )
					.removeClass( (thisHTML != hint)?'notext':'' )
					.val( (thisHTML != hint)?thisHTML:'' )
					;
					
			})
			.blur(function(){
				var hint = 'keywords:';
				var thisHTML	= $( this ).val();
				$( this )
					.addClass( (thisHTML != '')?thisHTML:'notext' )
					.val( (thisHTML != '') ? thisHTML : hint )
					;	
			});
	});
	
	// jwg 2009-11-19 -- an onClick that works with IE, Safari and Chrome ...
	if ($("#title_note_close")) { 
		// Used in actions\all.php and other locations where title note is present.
		// This closes the title note and saves fact of particular closure in a cookie to avoid re-display.
		$("#title_note_close").css("cursor", "pointer").click(function() { 
			var closer = $("#title_note_close");
			var whatClosed = '';
			if (closer.hasClass('close_all')) {
				whatClosed = 'all';
			} else if (closer.hasClass('close_public')) {
				whatClosed = 'public';
			} else if (closer.hasClass('close_showstream')) {
				whatClosed = 'showstream';
			} else {
				alert("Unknown note closed... please report to site owners.");
				return;
			}
			var ourdomain = getCurrentDomain();

			pastCloses = GetCookie('closed_notes');
			if (!(pastCloses == '') || (pastCloses.indexOf(whatClosed + ',') == -1)) {
				SetCookie('closed_notes', pastCloses + whatClosed + ',', null, ourdomain);
			}
			$("#title_note").removeClass('display_block');
			$("#title_note").addClass('display_none');
		});
	}	
	
	
	// jwg 2009-11-21
	if ($("#attachment_list")) { 
		$("#attachment_list").css("cursor", "pointer").click(function() { 
			toggle_section($("#attachment_list"), $("#attachment_list_body"));
		});
	}	
	
	// jwg 2009-11-21
	function  toggle_section(section_header, section_body) {
		// todo - put icon in header and reverse polarity dn vs up
		
		// open or close section based on presence of display_none class
		if (section_body.hasClass('display_none')) {
			section_body.removeClass('display_none');
			section_body.addClass('display_block');
		} else {
			section_body.removeClass('display_block');
			section_body.addClass('display_none');
		}
	}
	
	// count character on keyup
	function counter(event){
		docountupdate(event);	// jwg.. moved below for use by other functions outside of onready()
	}

	function submitonreturn(event) {
		if (event.keyCode == 13) {
			$("#form_notice").submit();
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		return true;
	}

	var doCounter = false; // jwg
	if ($("#notice_data-text").length) {
		$("#notice_data-text").bind("keyup", counter);
		//$("#notice_data-text").bind("keydown", submitonreturn); // 2009-10-29 .. reinstated for bj .. jwg 2009-08-30 -- noop to allow Enter w/o submit
		doCounter = true;
	}
	// jwg -- add counter to bio in registration form and edit profile settings -- piggy back on this function -- 2009-08-25
	if (document.getElementById('form_settings_profile') || document.getElementById('form_register')) {
		$("#bio").bind("keyup", counter);
		doCounter = true;
	}
	if (doCounter) { // jwg
		// run once in case there's something in there
		counter(null);
	}
 
 /* jwg 2010-02-26 -- do not refocus to notice area -- it is distracting if user has scrolled down the page        
  if(document.getElementById('notice_data-text') && ($('body')[0].id != 'conversation')) { // jwg -- added element existence test to conditionals
            $("#notice_data-text").focus();
  }
 */

	// Make Enter key on register form cause alert to click a chosen button... 
	// We could just submit the form, but later might want to ask for more info where newlines are desired...
	if ($("#newcaptcha") && $("#form_register")) { // try to get default behavior or Enter key to submit the registration.. not request new captcha
		$("#form_register").bind("keydown", submitregistration);
	}
	function submitregistration(event) {
		if (event.keyCode == 13) {
			alert("You must click one of the buttons.");
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		return true;
	}

	// XXX: refactor this code

	// jwg 2010-02-12
	var rtoptions = { dataType: 'xml',
					   timeout: '120000',
					   error: function (xhr, textStatus, errorThrown) {

											if (textStatus == "timeout") {
																			alert ("Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists");
											} else {
									
												// JWG NOTE .. IF YOU GET JS ERROR on line after next due to parse error, uncomment the debug alert
												//document.write('<pre>');
												//document.write(xhr.responseText);
												//document.write('</pre>');
																			
												//alert("in rtoptions error function. status is "+xhr.status+", "+xhr.statusText+", "+textStatus);
												if ((xhr.status == 200) && (textStatus == 'parsererror')) {
													errmsg = getErrorMsg(xhr.responseText);
													if (errmsg) {
														alert("Error: " + errmsg);
														return;
													} else {
														document.location.reload(true);    // reload page -- nice affect of showing latest post ...
														return; // avoid tragedy below .. do not attempt referece to responseXML if parseerror ...									
													}
												}	

												if (!xhr.responseXML) { // added to deal w/ parse errors...
													alert("Sorry! We encountered a program problem posting your notice.. "+textStatus+" "+errorThrown+" "+xhr.statusText); 
												} else {
													var HTTP20x30x = [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307];
													try 
													{ 
														if ($(".error", xhr.responseXML).length > 0) {// jwg preck exist .. TBD
															try {
																$('#form_notice').append(document._importNode($(".error", xhr.responseXML).get(0), true));
															} catch (e) {
																alert(e);
															}
														} else {
															if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																alert("Sorry! We had trouble sending your notice ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
															}
														}
													} catch(err) { // assuming error was on first if of try
														var x = xhr.responseText.indexOf('class="error"');
														if (x > 0) {
															x = xhr.responseText.indexOf('>',x);
															var y = xhr.responseText.indexOf('<',x+1);
															if (y > x) {
																alert(xhr.responseText.substr(x+1,y-(x+1)));
															}
														} else {
															if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																alert("Sorry! We had trouble sending your notice ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
															}																						
														}
													}
												}
											}
									},
					   success: function(xml) {	

					   						if ($("#error", xml).length > 0) {
													var result = document._importNode($("p", xml).get(0), true);
													result = result.textContent || result.innerHTML;
													alert("error: " + result);
												}
												else {
												    if ($("#command_result", xml).length > 0) { // note - the fact it is "command_result" instead of "error" implies ok...
												    	
															var result = document._importNode($("p", xml).get(0), true);
															result = result.textContent || result.innerHTML;
															alert(result);
                            	return;
                            }
												}
										}
					   };

	var favoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var dis = new_form.id;
												var fav = dis.replace('disfavor', 'favor');
												$('form#'+fav).replaceWith(new_form);
												$('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
												if ($("#notice_post_filter_list")) { // jwg -- in case it was faded for edit and they changed their mind
													$("#notice_post_filter_list").fadeTo(1, 1.0);  
												}
										}
					 }

	var disoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var fav = new_form.id;
												var dis = fav.replace('favor', 'disfavor');
												$('form#'+dis).replaceWith(new_form);
												$('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);
												if ($("#notice_post_filter_list")) { // jwg -- in case it was faded for edit and they changed their mind
													$("#notice_post_filter_list").fadeTo(1, 1.0); // fade in, in case prev faded out
												}
											  }
					 };

	var joinoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var leave = new_form.id;
												var join = leave.replace('leave', 'join');
												$('form#'+join).replaceWith(new_form);
												$('form#'+leave).ajaxForm(leaveoptions).each(addAjaxHidden);
											  }
					 };

	var leaveoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var join = new_form.id;
												var leave = join.replace('join', 'leave');
												$('form#'+leave).replaceWith(new_form);
												$('form#'+join).ajaxForm(joinoptions).each(addAjaxHidden);
											  }
					 };
	
	// jwg 
	function handleError(xhr,textStatus,errorThrown) {
																		if (textStatus == "timeout") {
																			alert ("Sorry! Your request timed out. Please try again, and contact the site administrator if this problem persists");
																		} else {
																			if ((xhr.status == 200) && (textStatus == 'parsererror')) {
																				errmsg = getErrorMsg(xhr.responseText);
																				if (errmsg) {
																					alert("Error: " + errmsg);
																					return false;
																				} else {
																					//document.write('<pre>');
																					document.write(xhr.responseText);
																					//document.write('</pre>');
																					//document.location.reload(true);    // reload page -- nice affect of showing latest post ...
																					return false; // avoid tragedy below .. do not attempt referece to responseXML if parseerror ...									
																				}
																			}	
																			if (!xhr.responseXML) { // added to deal w/ parse errors...
																				alert("Sorry! We encountered a program problem posting your notice.. "+textStatus+" "+errorThrown+" "+xhr.statusText); 
																			} else {
																				var HTTP20x30x = [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307];
																			 	try 
																			 	{ 
																					if ($(".error", xhr.responseXML).length > 0) {// jwg preck exist .. TBD
																						try {
																							$('#form_notice').append(document._importNode($(".error", xhr.responseXML).get(0), true));
																						} catch (e) {
																							alert(e);
																						}																						
																					} else {
																						if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																							alert("The following error occured. ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
																						}
																					}
																				} catch(err) { // assuming error was on first if of try
																					var x = xhr.responseText.indexOf('class="error"');
																					if (x > 0) {
																						x = xhr.responseText.indexOf('>',x);
																						var y = xhr.responseText.indexOf('<',x+1);
																						if (y > x) {
																							alert(xhr.responseText.substr(x+1,y-(x+1)));
																						}
																					} else {
																						if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																							alert("The following error occured. ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
																					
																						}
																					}
																				}
																		 	}
																		}
																		return false; // tbd
	}							


	function addAjaxHidden() {
		var ajax = document.createElement('input');
		ajax.setAttribute('type', 'hidden');
		ajax.setAttribute('name', 'ajax');
		ajax.setAttribute('value', 1);
		this.appendChild(ajax);
	}

	$("form.form_retweet").ajaxForm(rtoptions);			/* jwg 2010-02-12 */
	$("form.form_favor").ajaxForm(favoptions);
	$("form.form_disfavor").ajaxForm(disoptions);
	$("form.form_group_join").ajaxForm(joinoptions);
	$("form.form_group_leave").ajaxForm(leaveoptions);
	$("form.form_retweet").each(addAjaxHidden);			/* jwg 2010-02-12 */
	$("form.form_favor").each(addAjaxHidden);
	$("form.form_disfavor").each(addAjaxHidden);
	$("form.form_group_join").each(addAjaxHidden);
	$("form.form_group_leave").each(addAjaxHidden);

	$("#form_user_nudge").ajaxForm ({ dataType: 'xml',
		beforeSubmit: function(xml) { $("#form_user_nudge input[type=submit]").attr("disabled", "disabled");
									  $("#form_user_nudge input[type=submit]").addClass("disabled");
									},
		success: function(xml) { $("#form_user_nudge").replaceWith(document._importNode($("#nudge_response", xml).get(0),true));
							     $("#form_user_nudge input[type=submit]").removeAttr("disabled");
							     $("#form_user_nudge input[type=submit]").removeClass("disabled");
							   }
	 });
	$("#form_user_nudge").each(addAjaxHidden);
/* recent
	var Subscribe = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { 
					  														$(".form_user_subscribe input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_subscribe input[type=submit]").addClass("disabled");
																	    },
					  success: function(xml) { 
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled"); // jwg 2010-05-07 - moved here from below
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
					  						 // jwg 2010-01-21 -- refresh after success
					  	           document.location.reload(true);    // which pretty much obviates the above...                                                        	return;
                         return;
										     },
					   timeout: '120000',
					   error: function (xhr, textStatus, errorThrown) {
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled"); // jwg 2010-05-07 - added
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
					   						return handleError(xhr,textStatus,errorThrown);
					   						 }
					};

	var UnSubscribe = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { 
																				$(".form_user_unsubscribe input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unsubscribe input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { 
												 $(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");	// jwg 2010-05-07 - moved here from below
												 $(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
					    					// jwg 2010-01-21 -- refresh after success
					    					document.location.reload(true);    // which pretty much obviates the above...                                                        	return;
                        return;
 										     },
					   timeout: '120000',
					   error: function (xhr, textStatus, errorThrown) {
									$(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");	// jwg 2010-05-07 - added
									$(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
					   			return handleError(xhr,textStatus,errorThrown);
					   						 }
					
					  };
*/
/* really old version */

	var Subscribe = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { $(".form_user_subscribe input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_subscribe input[type=submit]").addClass("disabled");
																	    },
					  success: function(xml) { var form_unsubscribe = document._importNode($('form', xml).get(0), true);
										  	   var form_unsubscribe_id = form_unsubscribe.id;
											   var form_subscribe_id = form_unsubscribe_id.replace('unsubscribe', 'subscribe');
											   $("form#"+form_subscribe_id).replaceWith(form_unsubscribe);
											   $("form#"+form_unsubscribe_id).ajaxForm(UnSubscribe).each(addAjaxHidden);
											   $("dd.subscribers").text(parseInt($("dd.subscribers").text())+1);
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled");
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
										     }
					};

	var UnSubscribe = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { $(".form_user_unsubscribe input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unsubscribe input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { var form_subscribe = document._importNode($('form', xml).get(0), true);
										  		 var form_subscribe_id = form_subscribe.id;
												 var form_unsubscribe_id = form_subscribe_id.replace('subscribe', 'unsubscribe');
												 $("form#"+form_unsubscribe_id).replaceWith(form_subscribe);
												 $("form#"+form_subscribe_id).ajaxForm(Subscribe).each(addAjaxHidden);
												 $("#profile_send_a_new_message").remove();
												 $("#profile_nudge").remove();
											     $("dd.subscribers").text(parseInt($("dd.subscribers").text())-1);
												 $(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");
												 $(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
											   }
					  };




	$(".form_user_subscribe").ajaxForm(Subscribe);
	$(".form_user_unsubscribe").ajaxForm(UnSubscribe);
	$(".form_user_subscribe").each(addAjaxHidden);
	$(".form_user_unsubscribe").each(addAjaxHidden);


	var Block = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { $(".form_user_block input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_block input[type=submit]").addClass("disabled");										    
																	    },
					  success: function(xml) { 
					  	$(".form_user_block input[type=submit]").removeAttr("disabled");	// jwg 2010-05-07 
							$(".form_user_block input[type=submit]").removeClass("disabled");	
							
							$('#form_notice').append(document._importNode($("form", xml).get(0), true));
					  	  //         document.location.reload(true);               
                         return;
										     },
					   timeout: '120000',
					   error: function (xhr, textStatus, errorThrown) {
					  			$(".form_user_block input[type=submit]").removeAttr("disabled");	// jwg 2010-05-07 
									$(".form_user_block input[type=submit]").removeClass("disabled");	
					   			return handleError(xhr,textStatus,errorThrown);
					   						return true;
					   						 }
					};

	var Unblock = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { $(".form_user_unblock input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unblock input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { 
					    					document.location.reload(true);                              
                        return;
										     },
					   timeout: '120000',
					   error: function (xhr, textStatus, errorThrown) {
					   	
					   			return handleError(xhr,textStatus,errorThrown);
											  }
					  };

	$(".form_user_block").ajaxForm(Block);
	$(".form_user_unblock").ajaxForm(Unblock);
	$(".form_user_block").each(addAjaxHidden);
	$(".form_user_unblock").each(addAjaxHidden);

	// jwg 2010-05-18
	if (document.getElementById('uploader')) { // avoid js error
		var domparts = getCurrentDomain().split('.');
		if (domparts.length > 1) {
			var mydomain = domparts[domparts.length-2] + '.' + domparts[domparts.length-1];
			document.domain = mydomain;
		}
	}			
	// jwg 2010-05-28
	var goback = document.location.href; // document.referrer;  
	//if ((goback == null) || (goback == undefined) || (goback == '')) goback = document.location.href;
	//alert("goback="+goback); // DEBUG	
	
	// jwg 2010-05-28
	function getExtension(filename) {
		var x = filename.lastIndexOf('.');
		var ext = null;
		if (x > -1) {
			ext = filename.substr(x+1);
		}
		return ext;
	}	
	

	var validated_callback = null;
	if ($("#form_notice")) {	// use something that is not masked by jquery closure and can be set by validation callback
		$("#form_notice").removeClass('validated');
	}
	
	var PostNotice = { dataType: 'xml',
					   	//beforeSubmit: function(formData, jqForm, options) { 
					   	// jwg 2010-05-18
					   	beforeSerialize: function() { // catch it before original form values are serialized so can modify content 
					   												//alert("in beforeserialize");

																		// jwg 2010-07-30
					   												if (!$("#form_notice").hasClass('validated')) {
					   													ckLoggedIn('post_approved()','form_notice');
					   													return false;
					   												}
					   												$("#form_notice").removeClass('validated');
					   																		
					   												if (!$("#form_notice").hasClass("processing")) {
																		   $("#form_notice").addClass("processing");
																		   $("#notice_action-submit_tab2").attr("disabled", true);	// jwg 2010-05-07 ... changed to true from 'disabled' ?
																		   $("#notice_action-submit_tab2").addClass("disabled");
																		   $("#postbutton").addClass("disabled");	// jwg 2010-09-01
																		   hideDiv('copy_of_notice');

																			// jwg 2010-05-18 -- handle post attachment file uploads to partner sites
																		  // Use iframes in noticeform for cross-subdomain media upload to subdomain proxy to partner sites 
																		  // Locate expected iframe submission form elements sourced from http://upload.<site.server>/upload.html
																		  var iframeEl = document.getElementById('uploader');	// submission form
																		  var iframeEl2 = document.getElementById('upldresp');// response form (so retain submit settings at error)
																		  var uploadform = null;
																		  var responseform = null;
																			var el_msg = null;
																			var el_tags = null;
																			var el_title = null;
																			var el_cats = null;
																			var el_cuid = null;
																			var el_token = null;
																			var el_callback = null;
																			var el_audfile = null;
																			var el_imgfile = null;
																			var el_vidfile = null;
																			var el_docfile = null;
																			var el_private = null;	// jwg 2010-06-20
																			
																			if (iframeEl) { // allow for absence of media upload iframe
																				var oDoc = iframeEl.contentWindow || iframeEl.contentDocument;
	    																	if (oDoc.document) { oDoc = oDoc.document; }
																				uploadform = oDoc.getElementById('upload_form');
																				el_msg = oDoc.getElementById('msg');
																				el_tags = oDoc.getElementById('tags');
																				el_title = oDoc.getElementById('title');
																				el_cats = oDoc.getElementById('cats');
																				el_cuid = oDoc.getElementById('cuid');
																				el_token = oDoc.getElementById('token');
																				el_callback = oDoc.getElementById('callback');
																				el_aud = oDoc.getElementById('audiofile');
																				el_img = oDoc.getElementById('imagefile');
																				el_vid = oDoc.getElementById('videofile');
																				el_doc = oDoc.getElementById('docfile');
																				el_private = oDoc.getElementById('private'); // jwg 2010-06-20
																		
																				// Determine if upload file(s) set in the submit form
																				if (uploadform && (el_aud.value || el_img.value || el_vid.value || el_doc.value)) {
	
																					var isPrivate = $('#lockbutton').hasClass('selected'); 
																						
																					var noCredentials = $('#nada').val();
	
																				  // Use message, tags and upload file title for added info to accompany media
																				  
																					el_msg.value = $("#notice_data-text").val().substr(0,140); // set message to status text

																					if (($("notice_data-tags").length > 0) && ($("#notice_data-tags").val() == 'keywords:')) { // only kibitz words likely present ...
																						el_tags.value = '';	
																					} else {
																						el_tags.value = $( '#notice_data-tags' ).val();
																					}
																					
																					el_title.value = $("#attachment_title").val(); // set message to title value																			
																					
																					// no current category support 
																					
																					// user credentials 
																					el_cuid.value = $( '#cuid' ).val();
	
																					// session token
																					el_token.value = $("input#token").val();
	
																					//el_callback.value = 'alert'; // DEBUG
																					el_callback.value = 'upload_callback';			// name of local callback function for response
	
																					// private setting
																					el_private.value = (isPrivate) ? '1' : '0'; // jwg 2010-06-20
	
																					// test for video upload
																				  if (el_vid.value != '') {	
																				  	
																				  	if ($( '#cuid' ).val() == '') {
																				  		alert("Sorry. You must have a Twitter account setup to upload videos");
																					  	$("#form_notice").removeClass("processing");
																							$("#notice_action-submit_tab2").removeAttr("disabled");
																							$("#notice_action-submit_tab2").removeClass("disabled");
																							$("#postbutton").removeClass("disabled");	// jwg 2010-09-01
																					  	return false; // allow retry		
																				  	}
																				  	
																				  	var ext = getExtension(el_vid.value).toLowerCase();
																					  var videos =" 3gp 3g2 asf asx avi flv m4v mkv mov mp2 mp4 mpg mpeg ogv qt wmv ";
																					  if (ext && (videos.indexOf(' '+ext+' ') > -1)) { // it's a video we support at twitvid																	   
			
																				   			showDiv('uploading_media');	
																				   			uploadform.submit();																		   			
																				   			return false; // stop this upload ... but continue it after redrive submit from iframe 
																					   	
																					  } else {
																					  	alert("The video file you selected is not a type we support.");
																					  	$("#form_notice").removeClass("processing");
																							$("#notice_action-submit_tab2").removeAttr("disabled");
																							$("#notice_action-submit_tab2").removeClass("disabled");
																							$("#postbutton").removeClass("disabled");	// jwg 2010-09-01
																					  	return false;	// allow retry
																					  }
																					  
																					// test for audio upload
																					} else if (el_aud.value != '') {
																						
																				  	if ($( '#cuid' ).val() == '') {
																				  		alert("Sorry. You must have a Twitter account setup to upload audio and pictures");
																					  	$("#form_notice").removeClass("processing");
																							$("#notice_action-submit_tab2").removeAttr("disabled");
																							$("#notice_action-submit_tab2").removeClass("disabled");
																							$("#postbutton").removeClass("disabled");	// jwg 2010-09-01
																					  	return false; // allow retry		
																				  	}																				
																						
																						var ext = getExtension(el_aud.value).toLowerCase();
																				   	var audios = " mp3 mpa ra wav wma ";
																				   	if (ext && (audios.indexOf(' '+ext+' ') > -1)) { // it's an audio format we support at tweetmic
																				   		
																				   		if (el_img.value != '') {
																				   			var ext2 = getExtension(el_img.value).toLowerCase();
																				   			var images2 = " bmp gif jpg jpeg png psd psp tif tiff ";
																				   			if (ext2 && (images2.indexOf(' '+ext2+' ') == -1)) {
																				   				//alert("Only jpg or jpeg images may accompany audio uploads,\n which are stored at TweetMic.\n\n"+
																				   				//			"However, you can upload the audio file and then edit\nthis notice to attach the image separately.");
																							  	alert("The image file you have selected is not a supported type.");
																							  	$("#form_notice").removeClass("processing");
																									$("#notice_action-submit_tab2").removeAttr("disabled");
																									$("#notice_action-submit_tab2").removeClass("disabled");
																									$("#postbutton").removeClass("disabled");	// jwg 2010-09-01
																							  	return false;	// allow retry	
																				   			}
																				   		}
																				   		
																				   		showDiv('uploading_media');
																				   		uploadform.submit();									   		
																				   		return false; // stop this upload ... but continue it after redrive submit from iframe 
																				   	
																				   	} else {
																					  	alert("The audio file you selected is not a type we support.");
																					  	$("#form_notice").removeClass("processing");
																							$("#notice_action-submit_tab2").removeAttr("disabled");
																							$("#notice_action-submit_tab2").removeClass("disabled");
																							$("#postbutton").removeClass("disabled");	// jwg 2010-09-01
																					  	return false; // allow retry
																				   	}
																				   	
																				  // test for image upload  	
																				  } else if (el_img.value != '') {	
																				  	
																				  	if ($( '#cuid' ).val() == '') {
																				  		alert("Sorry. You must have a Twitter account setup to upload pictures");
																					  	$("#form_notice").removeClass("processing");
																							$("#notice_action-submit_tab2").removeAttr("disabled");
																							$("#notice_action-submit_tab2").removeClass("disabled");
																							$("#postbutton").removeClass("disabled");	// jwg 2010-09-01
																					  	return false; // allow retry		
																				  	}
																				  																					  	
																				  		
																				  	var ext = getExtension(el_img.value).toLowerCase();
																				   	var images = " bmp gif jpg jpeg png psd psp tif tiff ";
																				   	if (images.indexOf(' '+ext+' ') > -1) { // it's an image format we support at tweetphoto
																				   			showDiv('uploading_media');	
																				   			uploadform.submit();																		   			
																				   			return false; // stop this upload ... but continue it after redrive submit from iframe 
	
																				   	} else {
																					  	alert("The image file you selected is not a type we support.");
																					  	$("#form_notice").removeClass("processing");
																							$("#notice_action-submit_tab2").removeAttr("disabled");
																							$("#notice_action-submit_tab2").removeClass("disabled");
																							$("#postbutton").removeClass("disabled");	// jwg 2010-09-01
																					  	return false; // allow retry																			   		
																				   	}
																				   	
																				  // test for document upload  	
																				  } else if (el_doc.value != '') {	
																				  	
																				  	if ($( '#cuid' ).val() == '') {
																				  		alert("Sorry. You must have a Twitter account setup to upload an attachment");
																					  	$("#form_notice").removeClass("processing");
																							$("#notice_action-submit_tab2").removeAttr("disabled");
																							$("#notice_action-submit_tab2").removeClass("disabled");
																							$("#postbutton").removeClass("disabled");	// jwg 2010-09-01
																					  	return false; // allow retry		
																				  	}
																				  																					  		
																				  	var ext = getExtension(el_doc.value).toLowerCase();
																				   	var docs = ' csv doc docx efx log pdf psd pps ppt pptx rtf txt vcf wpd wps wks xlr xls xlsx ';
																				   
																				   	if (docs.indexOf(' '+ext+' ') > -1) { // it's an image format we support at tweetphoto
																				   			showDiv('uploading_media');	
																				   			uploadform.submit();																		   			
																				   			return false; // stop this upload ... but continue it after redrive submit from iframe 
	
																				   	} else {
																					  	alert("The document file you selected is not a type we support.");
																					  	$("#form_notice").removeClass("processing");
																							$("#notice_action-submit_tab2").removeAttr("disabled");
																							$("#notice_action-submit_tab2").removeClass("disabled");
																							$("#postbutton").removeClass("disabled");	// jwg 2010-09-01
																					  	return false; // allow retry																			   		
																				   	}
																				  }
																				  // fall through for no attachment case returning true
																				} else {
																					//alert("postnotice upload form not found..."); // DEBUG
																				}
																			} else { // already marked div as 'processing' so this is a redrive from submit by the iframe ... TBD
																			 	 
																			 	//alert("In postnotice beforeserialize ... and processing was already on"); // DEBUG
																 				// fall through to return true [continue with post]
																			}
																		}
																		// jwg 2010-06-06 -- turn off tag hint value at time of post
																		if (($("#notice_data-tags").length > 0) && ($("#notice_data-tags").val() == 'keywords:')) { 
																			$( "#notice_data-tags" ).val('');
																		}
																		//alert("postnotice::bforesubmit returning true"); // DEBUG
																		// jwg 2010-05-28
																		hideDiv('uploading_media'); // not likely necessary, but do it anyway
																		
																		if ($("#notice_update_type").val() == 'save_draft') {
																				$("#notice_update_type").val('edit');
																				showDiv('saving');
																		} else {
																				if ($("#isdraft") && ($("#isdraft").val() == '1')) {
																					$("#notice_update_type").val('send');
																				}
																				showDiv('posting_notice');
																		}
																		//alert("final reqtype is "+	$("#notice_update_type").val()); // DEBUG											
																		return true;
												 					},
					   timeout: '120000',
					   error: function (xhr, textStatus, errorThrown) {
																		//alert("in postnotice::error"); // DEBUG
																		
																		// jwg 2010-05-29
																		hideDiv('uploading_media'); // not likely necessary, but do it anyway
																		hideDiv('posting_notice');																		
																		hideDiv('saving');
					   												$("#form_notice").removeClass("processing");
																		$("#notice_action-submit_tab2").removeAttr("disabled");
																		$("#notice_action-submit_tab2").removeClass("disabled");
																		$("#postbutton").removeClass('disabled'); // jwg 2010-09-01
																		resetTagHint(); // jwg 2010-06-06
																		
																		if (textStatus == "timeout") {
																			alert ("Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists");
																		} else {
									
																			// JWG NOTE .. IF YOU GET JS ERROR on line after next due to parse error, uncomment the debug alert
																			//document.write('<pre>');
																			//document.write(xhr.responseText);
																			//document.write('</pre>');
																			
																			//alert("in postnotice error function. status is "+xhr.status+", "+xhr.statusText+", "+textStatus);
																			if ((xhr.status == 200) && (textStatus == 'parsererror')) {
																				errmsg = getErrorMsg(xhr.responseText);
																				if (errmsg) {
																					alert("Error: " + errmsg);
																					return;
																				} else {
																					if ($("#notice_data-text")) { 
																						$("#notice_data-text").val(""); 
																						counter(null);
																					}
																					if ($("#form_notice").hasClass("uploaded")) {
																						//alert("at 951 setting href"); // DEBUG
																						document.location.href = goback; // use referrer from last main page load.

                                         	} else { 
                                         		// jwg 2010-07-04 -- do not reload in this case T B D
                                         		//alert("at 954 reload");	// DEBUG
                                            document.location.reload(true);     // jwg 2010-07-14 - re-added - IE 'normal post' comes this route
                                          }
																					return; // avoid tragedy below .. do not attempt referece to responseXML if parseerror ...
											
																				}
																			}	

																			if (!xhr.responseXML) { // added to deal w/ parse errors...
																				alert("Sorry! We encountered a program problem posting your notice. "+textStatus+" "+errorThrown+" "+xhr.statusText); 
																				handleError(xhr,textStatus,errorThrown); // jwg 2010-07-03					
																			} else {
																				var HTTP20x30x = [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307];
																			 	try 
																			 	{ 

																					if ($(".error", xhr.responseXML).length > 0) {// jwg preck exist .. TBD
																						
																						// note .. we blow away in here by trying to get at responseXML if malformed ... i believe
																						try {
																							$('#form_notice').append(document._importNode($(".error", xhr.responseXML).get(0), true));
																						} catch (e) {
																							alert(e);
																						}

																					} else {

																						if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																							alert("Sorry! We had trouble sending your notice ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
																						} else {
																							$("#notice_data-text").val("");
																							counter(null);
																						}
																					}
																				} catch(err) { // assuming error was on first if of try

																							var x = xhr.responseText.indexOf('class="error"');
																							if (x > 0) {
																								x = xhr.responseText.indexOf('>',x);
																								var y = xhr.responseText.indexOf('<',x+1);
																								if (y > x) {
																									alert("NOTE: " + xhr.responseText.substr(x+1,y-(x+1)));
																								}
																							} else {
																								if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																								alert("Sorry! We had trouble sending your notice ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
																							}
								
																							//$("#notice_data-text").val("");
																							counter(null);
																							
																						}
																				}
																		 	}
																		}
																  },
					   success: function(xml) {	
					   						//alert("in postnotice::success"); // DEBUG
					   	
					   						// jwg 2010-05-29
												hideDiv('uploading_media'); // not likely necessary, but do it anyway
												hideDiv('posting_notice');							   	
					   						hideDiv('saving');
												// jwg 2010-05-07 moved here from below to insure reset
												$("#form_notice").removeClass("processing");
												$("#notice_action-submit_tab2").removeAttr("disabled");
												$("#notice_action-submit_tab2").removeClass("disabled");
												$("#postbutton").removeClass('disabled'); // jwg 2010-09-01
												resetTagHint(); // jwg 2010-06-06

					   						if ($("#error", xml).length > 0) {

													var result = document._importNode($("p", xml).get(0), true);
													result = result.textContent || result.innerHTML;
													alert("error: " + result);
													
												}	else {
														if ($("#marklet_redir", xml).length > 0) { // jwg 2010-02-26 handle redirect to refresh page after notice posted via bookmarklet
															
															var result = document._importNode($("p", xml).get(0), true);
															result = result.textContent || result.innerHTML;
															//$("#ajaxmessage").html("Message posted. One moment.<BR>Returning to previous page.");
															//$("#ajaxmessage").css({display:'none'}); // jwg .. just do it
							                //$("#ajaxmessage").fadeIn(500);
															//setTimeout('markletRedirect("'+result+'")',2500);			
																									
															markletRedirect(result)
															return;
															
												    } else if ($("#command_result", xml).length > 0) { // note - the fact it is "command_result" instead of "error" implies ok...
												    	
																									    var result = document._importNode($("p", xml).get(0), true);
																									    result = result.textContent || result.innerHTML;
																									    alert("Note: " + result);
																									    
																									  	// jwg 2009-12-16 -- show new message by page refresh  
																											if ($("#form_notice").hasClass("uploaded")) {
																												//alert("929 using goback="+goback);
																												document.location.href = goback; // use referrer from last main page load.                                          						
																												return; // jwg 2010-07-09 moved to here from below.. 
                                                      } else {
                                                      	// jwg 2010-07-04 - do not reload page in this case (e.g. DM initiated from notice list
                                                      	//alert("933 using reload");
                                                        //document.location.reload(true);    
                                                      }                                                    
                                                      //return;	// jwg 2010-07-09 fall through below for
                            }
                                                    else {
                                                         li = $("li", xml).get(0); 
                                                         //alert(li.id); // DEBUG                                                        
                                                         if (li && $("#"+li.id) && ($("#"+li.id).length == 0)) { // jwg protect against no li
                                                         	 // jwg -- note -- I might have caused this code not to be executed
                                                         	 // by putting the li into a <ul>...</ul> in newnotice.php for strict xml
                                                         	 // to solve another problem .... 
                                                         	 // ... it does not seem to go this way anymore ...
                                                            var notice_irt_value = $('#notice_in-reply-to').val();
                                                            var notice_irt = '#notices_primary #notice-'+notice_irt_value;
                                                            if($('body')[0].id == 'conversation') {
                                                                if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
                                                                    $(notice_irt).append('<ul class="notices"></ul>');
                                                                }
                                                                $($(notice_irt+' .notices')[0]).append(document._importNode(li, true));
                                                            
                                                            } else if ($('body')[0].id == 'showstream') { // jwg 2010-07-10 .. refresh page on this one
                                                           		if ($("#form_notice").hasClass("uploaded")) {
																																document.location.href = goback; // use referrer from last main page load.
                                                            	} else {
                                                            		document.location.reload(true);     // DO REFRESH FOR E.G. EDITED RESULTS W/IN TIMELINE
                                                            	}
                                                            } else {
                                                            	
                                                            	if ($('div.content-shownotice').length == 0) { // skip post insert on single notice view
                                                            		try {
                                                                	$("#notices_primary .notices").prepend(document._importNode(li, true));
                                                              	} catch (e) {
                                                              		alert(e);
                                                              	}
                                                              }
                                                            }
                                                            
                                                            $('#'+li.id).css({display:'none'}); // jwg .. just do it
                                                            $('#'+li.id).fadeIn(2500);
                                                            //NoticeReply(); // jwg 2010-04-28 TBD
                                                            NoticeAttachments();
                                                         		NoticeDataAttach(); // jwg 2009-12-30
                                 
                                                        } else {
                                                        	if ($("#notice_handled")) { // jwg .. look for special id from newnotice to indicate success
                                                            	var rdm = $("#remote_dm"); // jwg 2010-07-05
                                                            	if (rdm && (rdm.length > 0) && (rdm.val() != '1')) { // jwg put special message in hidden input field                                                         	
                                                            		alert("Note.. " + rdm.val()); 
                                                            		//hid = $("input", xml).get(0); // ck for hidden field (the only 'input' field in the ajax response
                                                            		//if (hid) {
                                                            		//	if ($(hid).val() != '1') {	// jwg avoid unnec alert ... 2010-06-02
                                                            		//		alert("Note.. " + $(hid).val());				// get the value of the hidden field
                                                               	//	}
                                                               	//}
                                                              }
                                                              //alert("before reload at 993: " + document.location.href); // DEBUG
                                                           		if ($("#form_notice").hasClass("uploaded")) {
                                                								//alert("987 using goback="+goback);
																																document.location.href = goback; // use referrer from last main page load.

                                                            	} else {
                                                            		
                                                            		// jwg 2010-07-04 -- do not reload page in this case ... TBD
                                                            		//alert("991 using reload");
                                                            		document.location.reload(true);     // DO REFRESH FOR E.G. EDITED RESULTS W/IN TIMELINE
                                                            	}
                                                            	return;
                                                        	} else {
                                                        		alert("Unexpected response: " + xml.responseText);
                                                        	}
                                                        }
													}
													closeUpShop(); // jwg 2010-07-09
													/* move this into closeUpShop ..
													$("#notice_data-text").val("");
    											$("#notice_data-attach").val("");
    											$("#notice_in-reply-to").val("");
                          $('#notice_data-attach_selected').remove();
                                                   	*/ 
                          counter(null);
												}
									}
					   };
	$("#form_notice").ajaxForm(PostNotice);
	$("#form_notice").each(addAjaxHidden);
  //NoticeReply(); // jwg 2010-04-28 TBD
  NoticeAttachments();
  NoticeDataAttach();
  NoticeLocationAttach(); // jwg 2009-12-30
   
  // jwg 2010-03-12
  if ($("#addr_lists")) {
			//$('#addr_lists').resizable().parent().draggable(); // this didn't work out for some reason ..
			if ($('#list').length || $('#mobile').length) {
				// address lists not draggable for narrow cases
			} else {
				$('#addr_lists').draggable();
			} 
  } 
 	// jwg 2010-04-07
 	if ($("#copy_of_notice")) {
 			$("#copy_of_notice").resizable(
 				{ dragHandle: true,
					handlers: {
						se: '#resizeSE',
						e: '#resizeE',
						ne: '#resizeNE',
						s: '#resizeS'
					}
				}
			);
 	}
 	// jwg 2010-04-28
  if ($("#markdownify")) {
			$('#markdownify').resizable(); 
  }  
  
	/* jwg 2010-05-06 keep text area opened to reveal controls on certain action pages */
	if ($('body')[0].id == 'postngo') {
		$( "#form_notice #notice_data-text" ).focus();
	}

		  
	if(typeof dvl_onready_last == 'function') dvl_onready_last(); 
			  
});

function resetTagHint() { // jwg 2010-06-06
	//$("#notice_data-tags").val('keywords:');
	var hint = 'keywords:';
	var thisHTML	= $("#notice_data-tags").val();
	$("#notice_data-tags")
		.addClass( (thisHTML != '')?thisHTML:'notext' )
		.val( (thisHTML != '') ? thisHTML : hint )
		;	
}

// jwg 2010-05-27
// Removes leading whitespaces
function LTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}
// Removes ending whitespaces
function RTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");	
}
	  
// jwg 2010-05-26
// handle callback response from iframed upload.<site.server>
// json_response success example:
//{
//	"rsp":"OK",
//	"cuid":"Az9NpqlLvy4P%6C*O>:Auw-=G?Zznfg54qw?uF521",
//	"source":"tweetmic",
//	"uploadid":"rht7xvow38h",
//	"siteurl":"http://tmic.fm/rht7xvow38h",
//	"audiourl":"http://api-stage.tweetmic.com/media/aurl_bz-rht7xvow38h.mp3",
//	"imageurl":"http://api-stage.tweetmic.com/media/aurl_bz-rht7xvow38h.jpg",
//	"videourl":""
//}
// json_response error example:
//{
//	"rsp":"NOK",
//	"err":".. error message .."
//}
function upload_callback(json_response) {
	//alert("json_response="+json_response); // DEBUG
	hideDiv('uploading_media');

	//if (json_response.trim().substr(0,1) != '{') { // does not work in IE
	if (LTrim(json_response).substr(0,1) != '{') {
		alert("Non-json response in upload_callback: "+json_response);
	
	} else {
		//alert('json_response: '+json_response); // DEBUG
		response = $.parseJSON(json_response);
		if (response.rsp) {
			if (response.rsp == 'NOK') {
				alert('Upload problem: '+response.err);
			
			} else if (response.rsp == 'OK') {
	
				var	mediatitle = ($("#attachment_title").val().length > 0) ? $("#attachment_title").val() + ' ' : '';
				var whatmedia = '';
				
				// use returned info to update in-process form data and re-submit the form			
				var addedurl = '';
				if (response.videourl != '') {
					addedurl += "\n" + mediatitle + response.videourl + ' '; 
					mediatitle = '';
					whatmedia = 'videos';
				}
				if (response.audiourl != '') {
					addedurl += "\n" + mediatitle + response.audiourl + ' ';
					mediatitle = '';
					whatmedia = 'recordings';
				}
				if (response.imageurl != '') {
					addedurl += "\n" + mediatitle + response.imageurl + ' ';
					mediatitle = '';
					if (whatmedia == '') whatmedia = 'pictures'; // allow for vid or aud as primary
				}
				if (response.docurl != '') {
					
					//addedurl += "\n" + mediatitle + response.docurl + ' ';
					addedurl += "\n" + response.docurl + ' '; // jwg .. in the case of document uploads handled locally we supply the title as url text
					mediatitle = '';
					whatmedia = 'documents';
				}
				if (addedurl != '') {
					/* -- for time being assume that clicking the media rendering/anchor will take a person to the source -- where 'more' are available 
					if (response.siteurl) {
						// T B D -- what to do with additional response info e.g. response.source (a link to further videos, audios, etc)
						// e.g. maybe send full json response in a separate form var with actual post ...
						addedurl += "\n" + 'more '+ whatmedia + ': ' + response.siteurl + ' ';
					}
					*/
					var updatedPost = $("#notice_data-text").val() + ' ' + addedurl; // example for twitvid case ... + ' http://twitvid.com/' + result.tv_mid;
					$("#notice_data-text").val(updatedPost); // replace post with updated post
					
					$("#notice_data-media_id").val(response.uploadid); // save uploaded media id
					$("#notice_data-media_loc").val(response.source);  // save partner site name (e.g. tweetphoto,twitvid,tweetmic,...)
				} else {
					alert("upload_callback did not update the post; no link to uploaded file.\nSo, the attachment is not referenced..."); // DEBUG
				}
				//alert("upload_callback submitting post"); // DEBUG
				$("form#form_notice").addClass("uploaded"); // set state flag to control reload
				$("form#form_notice").submit();
				return;
				
			} else {
				alert('Unexpected rsp value in upload_callback: '+response.rsp+', '+response.err);
			}
		} else {
			alert("Unexpected response in upload_callback: "+json_response);
		}
	}
	// unlock Send button for re-try
	$("#form_notice").removeClass("processing");
	$("#notice_action-submit_tab2").removeAttr("disabled");
	$("#notice_action-submit_tab2").removeClass("disabled");
	$("#postbutton").removeClass('disabled'); // jwg 2010-09-01
}

function markletRedirect(url) {
	document.location.href = url;
}

function ckLoggedIn(callback,formid) {
		var token = $("input#token").val();
		if (!token) { // jwg 2010-06-02
			alert('Note: your session needs to be restored before requesting this service.\nYou might be able to do this by simply refreshing the page.');
			return;
		} else {
			var requesturl = getBasePath() + "/ckstatus/"+token;
		  jQuery.ajax({
		         url:    requesturl,
		         error: function() { alert("error checking user logged-in status."); return -1; },
		         success: function(output) {
								var errmsg = getErrorMsg(output);
								if (errmsg) {
									alert('ckstatus error: ' + errmsg);
									return;	
								}
								if (LTrim(output).substr(0,1) != '{') {
									alert("Unexpected user status at logged-in check: "+output);
									return;
								} else {
									var response = $.parseJSON(output);
									if (response.rc) {
										if (response.rc == '1') {// user is logged in and token is ok
											$('#'+formid).addClass('validated');
											$('#'+formid).submit();
											return;
										}
										if (response.rc == '0') { // user must log in
											validated_callback = callback;
											document.getElementById('authenticator').innerHTML = "<iframe src='" + getBasePath() + "/authenticate'></iframe>";
											return; 
										
										} else {
											alert("unexpected return code checking logged-in status: "+response.rc);
											return;	
										}
									} else {
										alert("unexpected response checking logged-in status: "+output);
										return;		
									}
								}
		         },
		         async:   false
		    });       			
		}
}

function post_approved() {	// callback used by postNotice after good authenticate
	$("#form_notice").addClass('validated');
	$("#form_notice").submit();
}


function NoticeReply(notice_id_name, reply_type, reply_url) { // currently, reply_url is not used .. it was a backup strategy for click function
																							// jwg 2010-05-17 -- added private indicator 
		var notice = $('#'+notice_id_name);	// jwg 2010-04-28 -- setup for directly handling click
 
 		// jwg 2010-04-28 NoticeReply now called directly from clickable div instead of hooked into anchor click function
 		//                to overcome problem of anchor href being used instead of click function when page is too long to load in time...
    //if ($('#notice_data-text').length > 0 && ($('#content .notice_reply').length > 0) || ($('#content .notice_comment').length > 0) || ($('#content .notice_direct').length > 0)) {
    //    $('#content .notice').each(function() {
    //      var notice = $(this)[0];
            if ($('.notice_reply', notice)[0]) { // jwg 2009-11-24 -- make sure we really have something to add a click function to !!
            																		// pretty bizarre behavior for unexpected cases mistaken by original code .... that
            																		// drive the onclick function for replyto simply on any mousedown action on the page...

            		//$($('.notice_reply', notice)[0]).click(function() {
            		if (reply_type == 'reply') {	            			
                	// jwg 2010-01-19        			 
                	var remote_service = ($('.remote_replyto', notice).length > 0) ? $($('.remote_replyto', notice)[0]) : null;    			 
                	var nickname = ($('.intended_replyto', notice).length > 0) ? $($('.intended_replyto', notice)[0]) : null;
                	if (!nickname)    {    
                		if ($('.author .nickname', notice).length > 0) { 
                			nickname = $($('.author .nickname', notice)[0]);
                	    //alert('in notice_reply click. nicknameA=' + nickname.text()); <-- proper name here from notice list on local page
                		} else {  	
                			nickname = $('.author .nickname');
                	    //alert('in notice_reply click. nicknameB=' + nickname.text()); <-- seeing namename here from notice on broadcast page
                	  } 
                	}
                	var isPrivate = ($('.notice_private',notice).length > 0) ? true : false;
                	NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text(), (remote_service) ? remote_service.text() : null, null, isPrivate);
                	return false;
            		}
            		//});
            
            }
            if ($('.notice_direct', notice)[0]) { // jwg 2009-11-24 -- make sure we really have something to add a click function to !!
            																		// pretty bizarre behavior for unexpected cases mistaken by original code .... that
            																		// drive the onclick function for replyto simply on any mousedown action on the page...

            		//$($('.notice_direct', notice)[0]).click(function() {
                if (reply_type = 'dm') {
                	// jwg 2010-01-19        			 
                	var remote_service = ($('.remote_replyto', notice).length > 0) ? $($('.remote_replyto', notice)[0]) : null;    			 
									var dm = ($('.direct_message', notice).length > 0) ? $($('.direct_message', notice)[0]) : null; 
                	var nickname = ($('.intended_replyto', notice).length > 0) ? $($('.intended_replyto', notice)[0]) : null;
                	if (!nickname)    {    
                		if ($('.author .nickname', notice).length > 0) { 
                			nickname = $($('.author .nickname', notice)[0]);
                	    //alert('in notice_reply click. nicknameA=' + nickname.text()); <-- proper name here from notice list on local page
                		} else {  	
                			nickname = $('.author .nickname');
                	    //alert('in notice_reply click. nicknameB=' + nickname.text()); <-- seeing namename here from notice on broadcast page
                	  } 
                	}
                	NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text(), (remote_service) ? remote_service.text() : null, dm.text(), true);
                	return false;
            		}
            		//});
            }
            if ($('.notice_comment', notice)[0]) { // jwg 2009-11-24 -- make sure we really have something to add a click function to !!
            																		// pretty bizarre behavior for unexpected cases mistaken by original code .... that
            																		// drive the onclick function for replyto simply on any mousedown action on the page...

            		//$($('.notice_comment', notice)[0]).click(function() {
            		if (reply_type == 'comment') {
            			var isPrivate = ($('.notice_private',notice).length > 0) ? true : false;
									var nickname = ($('.intended_replyto', notice).length > 0) ? $($('.intended_replyto', notice)[0]) : null;
                	if (nickname)    { // pass directly from intended_replyto -- assuming !'s or @'s are in place
                		NoticeCommentSet(nickname.text(), $($('.notice_id', notice)[0]).text(),isPrivate);
                	} else {    
	            			
	            			if ($('.group_name', notice)[0]) { // jwg 2010-01-14 -- handle comment that targets a group
	            				NoticeCommentSet('!'+$($('.group_name', notice)[0]).text(), $($('.notice_id', notice)[0]).text(), isPrivate);
	            			} else {
	            				var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname');
	                		NoticeCommentSet(nickname.text(), $($('.notice_id', notice)[0]).text(),isPrivate);
										}
									}
                	return false;
                }
            		//});
            }
//        });
//    } 
}


function addAttachment() {
				if ($("#notice_action-attach_browse").hasClass('display_none')) {
					$("#notice_action-attach_browse").removeClass('display_none');
					$("#notice_action-attach_browse").addClass('display_block');
					$("#notice_action-attach_request").removeClass('attach_open');
					$("#notice_action-attach_request").addClass('attach_close');
					$("#notice_action-attach_request").blur();
				} else {
					$("#notice_action-attach_browse").removeClass('display_block');
					$("#notice_action-attach_browse").addClass('display_none');
					$("#notice_action-attach_request").removeClass('attach_close');
					$("#notice_action-attach_request").addClass('attach_open');
					
					if ($('#show_post_form').length) {
						hideDiv('form_notice');
						hideDiv('list_shim');
						showDiv('list_shimx');
					}		
					$("#notice_action-attach_request").blur();
				}	
}

function showAddrlist() {
			var uid = $("#recipient_request_user").val();
			$("#notice_action-recipient_request").blur();
			showAddrLists(uid); // * means 'for logged in user'
}

function toggleScheduler() {
			if ($("#schedule_time").hasClass('display_none')) {
				showDiv('schedule_time');
			} else {
				hideDiv('schedule_time');
			}
}

function NoticeReplySet(nick,id,service,dm,isPrivate) 
{
	
		//alert("isPrivate="+isPrivate); // DEBUG
	
// had difficulty adding proper regex to allow for special case of nick form: "!groupname @othername" -- for sending Reply to group and notice author.
//	rgx_username = /^[!0-9a-zA-Z\-_.]+(?:\s\@[0-9a-zA-Z\-_.]+)?$/;	// permit nick to contain ! (to allow NoticeReply to flag fact that a group is being replied to
//	if (nick.match(rgx_username)) {

		var no_intext_replyto = false; // normally add recipient name at start of text area 

		if ((nick.substr(0,1) == '!') || (nick.substr(0,1) == '@') || (nick.substr(0,1) == '/')) {			// assume full set of recipients already spec'd -- from "intended_replyto" list
			replyto = nick + "\r\n"; // jwg 2010-06-25 newline instead of space																														// jwg 2010-01-28 .. include / in considerations
			if (dm && service) { // jwg 2010-07-09 - also set it here
				no_intext_replyto = true;
			}
		} else {
			//replyto = "@" + nick + " ";
			if (service) {
				if (dm) {
					no_intext_replyto = true; // jwg == try turnoff all in-text replyto
				}
				if (service == 1) {
					replyto = "@" + nick + " ";	// jwg 2010-01-28 .. continue to support @ on basis of to external
				} else {
					replyto = nick + " ";
				}
			} else {
				replyto = "/" + nick + "\r\n";	// jwg 2010-01-28 .. support /name internally
			}
		}
//		$("#notice_data_legend").text('Discover & Share with the World');
		if (dm) {
			$("#notice_dm").val(dm);
			if ($("#notice_data_legend")) {
				$("#notice_data_legend").text('SENDING DM TO: '+replyto);
			}
			if (dm == 'L') { // local dm - turn off remote send checks
				turnOffPostTos();
			}
			if (!isPrivate) isPrivate=true;
		}
		if ($("#notice_data-text").length) {
			// jwg 2010-01-25 - for use with notice form on a search results page -- initially not displayed
			if ($("#form_notice") && $("#form_notice").hasClass('display_none')) {
				$("#form_notice").removeClass('display_none');
				$("#form_notice").addClass('display_block');
			}
			
			if (service && isPrivate && !dm) {
				alert("setting non-private");
				setPrivacy(false); // jwg 2010-07-23 -- if this is a reply to a protected import and not a DM, default the reply to public (like twitter)	
			} else {
				
				//alert("setting privacy to "+isPrivate); // DEBUG
				setPrivacy(isPrivate); // jwg 2010-03-26
			}
			
			resetBroadcast(); // jwg -- also make sure button not still set for an edit...

			// jwg 2010-01-19 -- turn off all broadcast selections except target service if replyto external service
			if (service) {
				var nms = new Array(null, 'twitter', 'facebook', null, 'blogspot', 'myspace',
    							 'wordpress', 'tumblr', 'livejournal', 'typepad', 
    							 'linkedin',null,null,null,null,null);	
				for (var i = 1; i < 15; i++) {
					if (nms[i]) {
						//var x = document.getElementById('postto_' + nms[i]);
						var x = document.getElementById('postto_' + i); // jwg 2010-05-06
						if (x) {
							if (i == parseInt(service)) {
								x.checked = true;
								if (!$('.postto_network.'+nms[i]).hasClass('selected')) {
									$('.postto_network.'+nms[i]).addClass('selected');
								}
							} else {
								x.checked = false;
								$('.postto_network.'+nms[i]).removeClass('selected');
							}
						}
					}
				}
			}

			loadCopyOfNotice(id);
			
			window.scroll(0,0); // horizontal and vertical scroll targets
			
			if (!no_intext_replyto) { // jwg 2010-06-22 -- omit in-text replyto for some cases .. 
				$("#notice_data-text").val(replyto);
			}
		
			$("#form_notice input#notice_in-reply-to").val(id);
			//$("#notice_data-text").focus();

			var node = document.getElementById('notice_data-text');
			setCursorPosition(node,replyto.length-1);				

			// jwg 2010-05-05
			showNoticeCtls();

			return false;
		}
//	}
	return true;
}

// jwg 2010-05-05
function showNoticeCtls() {

	$('#notice_data-text').focus();

}

// jwg 2010-07-16
function setupPost(nickname) {
	if ($("#notice_data-text")) {  
		$("#notice_data-text").val('/'+nickname+' ');
		$("#notice_data-text").focus();
	}
}

// jwg 2010-04-05
function loadCopyOfNotice(notice_id) {
	if ($("input#token").length) {
		var token = $("input#token").val();
		if (!token) { // jwg 2010-06-02
			alert('Note: your session needs to be restored before posting a new notice.\nYou might be able to do this by simply refreshing the page.');
		}
		var requesturl = getBasePath() + "/getnotice/rendered/"+notice_id+"/"+token;
		$("#old_notice_text").load(requesturl,{},
						function(output) {
								var errmsg = getErrorMsg(output);
								if (errmsg) {
									alert(errmsg);
									return;
								}  
						}
			);	
		showDiv('copy_of_notice');
	} else {
		alert("missing token");
	}
}

// jwg 2010-04-27
function importPage() {
	if ($("input#token").length) {
		var token = $("input#token").val();
		var url = prompt("Enter a web page address:", '');
		if (!url) return;
		var requesturl = getBasePath() + "/getmarkdown/?token="+token+'&uri='+escape(url);
		$("#markdownify_result").load(requesturl,{},
						function(output) {
								var errmsg = getErrorMsg(output);
								if (errmsg) {
									alert(errmsg);
									return;
								}  
						}
			);	
		showDiv('markdownify');
	} else {
		alert("missing token");
	}
}

// jwg 2010-04-05
function showAlerts(user_id) {
	if ($("input#token").length) {
  	var token = $("input#token").val();
		var requesturl = getBasePath() + "/getalerts/"+user_id+"/?token="+token;
		$("#alertDisplay").load(requesturl,{},
						function(output) {
								var errmsg = getErrorMsg(output);
								if (errmsg) {
									alert(errmsg);
									return;
								}  else {
									//alert(output);
								}
						}
			);	
		showDiv('alertDisplay');
	} else {
		alert("missing token");
	}
}

// jwg 2010-04-05 -- test getuserinfo
function showUserInfo(profile_id) {
	if ($("input#token").length) {
		var token = $("input#token").val();
		var requesturl = getBasePath() + "/getuserinfo/"+profile_id+"/"+token;
		$("#alertDisplay").load(requesturl,{},
						function(output) {
								var errmsg = getErrorMsg(output);
								if (errmsg) {
									alert(errmsg);
									return;
								}  
						}
			);	
		showDiv('alertDisplay');
	} else {
		alert("missing token");
	}
}

// jwg 2010-03-30
function turnOffPostTos() {
				var nms = new Array(null,'twitter', 'facebook', null, 'blogspot', 'myspace',
    							 'wordpress', 'tumblr', 'livejournal', 'typepad', 
    							 'linkedin',null,null,null,null,null);	
				for (var i = 1; i < 15; i++) {
					if (nms[i]) {
						//var x = document.getElementById('postto_' + nms[i]);
						var x = document.getElementById('postto_' + i); // jwg 2010-05-06
						if (x) {
							x.checked = false;
							$('.postto_network.'+nms[i]).removeClass('selected');
						}
					}
				}	
}


// jwg 2009-11-27
function NoticeCommentSet(nick,id,isPrivate) {

	if ($("#notice_data-text").length) {
	//		$("#notice_data_legend").text('Discover & Share with the World');
			if ($("#form_notice") && $("#form_notice").hasClass('display_none')) {
				$("#form_notice").removeClass('display_none');
				$("#form_notice").addClass('display_block');
			}	
	}

	//rgx_username = /^[!0-9a-zA-Z\-_.]*$/; // jwg 2010-01-14 .. allow for presence of leading !
	rgx_username = /^(?:[A-Za-z0-9_\-\.\!]|\xc3[\x80-\xbf])*$/; // jwg 2010-05-11.. allow for european chars
	if (nick.match(rgx_username)) {
		var replyto = ''; // jwg 2010-01-15 .. no need for : (tbd)
		//var replyto = ": "; // simply start with a colon if this is a comment by same person who created the notice being commented on
									  // -- and this is sorted out by NoticeCommentSet caller to not call here if there should actually be a /reply
									  //    for the followup comment --
		if (nick.substr(0,1) == '!') {				 // jwg 2010-01-14 .. keep ! and name to form a group response
			replyto = nick + "\r\n";
		}
		
		setPrivacy(isPrivate); // jwg 2010-03-26		
		
		if ($("#notice_data-text").length) {
			
			resetBroadcast(); // jwg -- also make sure button not still set for an edit...

			loadCopyOfNotice(id);
				
			window.scroll(0,0); // horizontal and vertical scroll targets
			$("#notice_data-text").val(replyto);
			$("#form_notice input#notice_in-reply-to").val(id);
			
			//$("#notice_data-text").focus();
			// jwg 2010-05-05
			showNoticeCtls();
			
			return false;
		}
	}
	return true;
}
function NoticeAttachments() {

/*
    $.fn.jOverlay.options = {
        method : 'GET',
        data : '',
        url : '',
        color : '#000',
        opacity : '0.6',
        zIndex : 99,
        center : false,
        imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
        bgClickToClose : true,
        success : function() {
            $('#jOverlayContent').append('<button>&#215;</button>');  
            $('#jOverlayContent button').click($.closeOverlay);
        },
        timeout : 0,
        autoHide : true,
        css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
    };
*/
    $('#content .notice a.attachment').click(function() {
        //$().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
        // alternative to joverlay so person can continue use of site and see pic
        //alert($(this).attr('href'));
        
        // note -- we only come into this code if there was a class="attachment" on the url ...
        
      var url = $(this).attr('href'); // get actual downloadable file / url link
			if (url) {
				
        var x = url.lastIndexOf('.');		// to test extension
        var ext = url.substr(x+1);
        switch (ext) { 									// open document files and photoshop files and image files directly
        	case 'png':
        	case 'gif':
        	case 'jpg':
        	case 'jpeg':
      			window.open(url,	'_blank', "toolbar=0,menubar=0,scrollbars=1,resizable=1,status=1,location=1");
      			return false;
        		break;
        	
        	case 'doc': // Microsoft Word Document 
        	case 'docx': // Microsoft Word Open XML Document 
        	case 'log': // Log File 
        	case 'rtf': // Rich Text Format File 
        	case 'txt': // Plain Text File 
        	case 'wpd': // WordPerfect Document 
        	case 'wps': // Microsoft Works Word Processor Document 
        	case 'csv': // Comma Separated Values File 
        	case 'efx': // eFax Document 
        	case 'psd': // Photoshop
        	case 'pps': // PowerPoint Slide Show 
        	case 'ppt': // PowerPoint Presentation 
        	case 'pptx': // Microsoft PowerPoint Open XML Document 
        	case 'txt': // text file
        	case 'vcf': // vCard File 
        	case 'wks': // Microsoft Works Spreadsheet 
        	case 'xlr': // Microsoft Excel Spreadsheet 
        	case 'xls': // Microsoft Excel Spreadsheet 
        	case 'xlsx': // Microsoft Excel Open XML Document 
						return true;
						break;
					
				}							// open likely media files (pics, audio..) in new window w/ separate link for download
			}	
			//attid = $(this).attr('id').substring('attachment'.length + 1);
			attid = $(this).attr('id'); // jwg 2010-02-09 ... unintended side effect of other changes
			url = $('address .url')[0].href+'attachment/' + attid + '/ajax'; 
      window.open(url,	'_blank', "toolbar=0,menubar=0,width=500,height=500,scrollbars=1,resizable=1,status=1,location=1");
      return false;
    });

    var t;
    $("body:not(#shownotice) #content .notice a.thumbnail").hover(
        function() {
            var anchor = $(this);
            $("a.thumbnail").children('img').hide();
            anchor.closest(".entry-title").addClass('ov');

            if (anchor.children('img').length == 0) {
                t = setTimeout(function() {
                    //$.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
                      $.get($('address .url')[0].href+'attachment/' + anchor.attr('id') + '/thumbnail', null, function(data) {  // jwg 2010-02-10
                        anchor.append(data);
                    });
                }, 500);
            }
            else {
                anchor.children('img').show();
            }
        },
        function() {
            clearTimeout(t);
            $("a.thumbnail").children('img').hide();
            $(this).closest(".entry-title").removeClass('ov');
        }
    );
}

function NoticeDataAttach() {
    NDA = $('#notice_data-attach');
    NDA.change(function() {
        S = '<div id="notice_data-attach_selected" class="success"><code>'+$(this).val()+'</code> <button>&#215;</button></div>'; 
        NDAS = $('#notice_data-attach_selected');
        (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#form_notice').append(S);
        $('#notice_data-attach_selected button').click(function(){
            $('#notice_data-attach_selected').remove();
            NDA.val('');
        });
    });
}

// jwg -- copied from status.net 0.92 util.js
function  NoticeLocationAttach() {
					if ($('#no_geo_location')) {
						// do nothing in this case
					} else {
						/* -- do not do this -- reveals too much information usable to thieves --
            if(navigator.geolocation) { 
            	navigator.geolocation.getCurrentPosition(function(position) {
	            	if ($('#notice_data-lat')) {
	            		$('#notice_data-lat').val(position.coords.latitude);
	                $('#notice_data-lon').val(position.coords.longitude);
	              }
	              var curcookloc = GetCookie('geolocation');
								var currealloc = position.coords.latitude + ',' + position.coords.longitude;
	              if (curcookloc != currealloc) {
		              SetCookie('geolocation',currealloc, null, getCurrentDomain());
		            }
	            });
	         	}
	         	*/
	       }
}

// jwg 2010-01-24
function messageReply(message_id, to_id, nickname) { // jwg 2010-06-06 added nickname
	// not currently using the message_id .. which is id of message being replied to .. would require new field to track it in message
	// to_id is the profile id of the intended recipient. Use that to select proper option in select dropdown of message form
	if (!$('#to')) {
		alert("Could not locate recipient select list.");
	} else {
		//$('#to').val(to_id); // jwg 2010-03-22 new approach with no dropdown list ...
		setMsgTo(to_id,nickname); // jwg 2010-06-06
		/*
		var tolist = document.getElementById('to');
		found = 0;
		for (var i=0; i<tolist.length; i++){
			if (tolist[i].value == to_id) {
				tolist.selectedIndex = i;
				found = 1;
				break;
			}
		}
		if (found==0) {
			alert("The intended message recipient is not in your reply list");
			return;
		}
		*/
		$("#notice_data-text").focus();
	}
}
// jwg 2010-04-13
function close_action_menus() {
			if ($('#user_action_menu_vis') && ($('#user_action_menu_vis').val() != '0')) {
				$('#user_action_menu_vis').val('0');
				$('.user_action_menu').each(function(){
					$(this).removeClass('display_block');
					$(this).addClass('display_none');
				});
			}
}

// jwg 2010-04-13
function showUserActionMenu(idnum) {
	toggleDiv('user_action_menu_'+idnum); // show-or-hide the action menu
	if ($('#user_action_menu_'+idnum).hasClass('display_block')) {
		setTimeout('set_vis_flag('+idnum+')',1000); // allow time for mouse-up so don't hide menu on current click
	}
}
function set_vis_flag(idnum) { 
	$('#user_action_menu_vis').val(idnum);
}

// jwg 2009-11-18
function showNoticeOptions(notice_id) {
	//$('#n-options-'+notice_id).removeClass('display_none');
	//$('#n-options-'+notice_id).addClass('display_block');
	$('#n-options-'+notice_id).removeClass('vis_hidden');
	$('#n-options-'+notice_id).addClass('vis_visible');
	$('#notice_author_actions-'+notice_id).removeClass('display_none');
	$('#notice_author_actions-'+notice_id).addClass('display_block');
	$('#s-buttons-'+notice_id).removeClass('vis_hidden');
	$('#s-buttons-'+notice_id).addClass('vis_visible');
	if ($('#user_action_menu_vis')) {
		var testid = parseInt($('#user_action_menu_vis').val());
		if ((testid != parseInt(notice_id)) && (testid != 0)) {
			close_action_menus();
		}
	}
	
}
function hideNoticeOptions(notice_id) {
	//$('#n-options-'+notice_id).removeClass('display_block');
	//$('#n-options-'+notice_id).addClass('display_none');
	$('#n-options-'+notice_id).removeClass('vis_visible');
	$('#n-options-'+notice_id).addClass('vis_hidden');
	$('#notice_author_actions-'+notice_id).removeClass('display_block');
	$('#notice_author_actions-'+notice_id).addClass('display_none');
	$('#s-buttons-'+notice_id).removeClass('vis_visible');
	$('#s-buttons-'+notice_id).addClass('vis_hidden');
}

// jwg 2010-03-09
function showDiv(idname) {
	$('#'+idname).removeClass('display_none');
	$('#'+idname).addClass('display_block');
}
function hideDiv(idname) {
	if ($('#'+idname)) {
		$('#'+idname).removeClass('display_block');
		$('#'+idname).addClass('display_none');
	}
}
function toggleDiv(idname) {
	if ($('#'+idname).hasClass('display_block')) {
		hideDiv(idname);
	} else {
		showDiv(idname);
	}
}

function setMsgTo(user_id,nickname) {
	$("#to").val(user_id);
	if ($("#notice_data-text").val().length == 0) {
		$("#notice_data-text").val('/'+nickname+' '+"\r\n");
	} else {
		$("#notice_data-text").val('/'+nickname+' '+$("#notice_data-text").val());
	}
}
// jwg 2010-03-10
function setAddrTo(nickname) {
	setPrivacy(true); // jwg 2010-06-29 - when a person uses their address list to set recipients, set the notice default private.
	if ($("#notice_data-text").val().length == 0) {
		$("#notice_data-text").val(nickname+' '+"\r\n");
	} else {
		$("#notice_data-text").val(nickname+' '+$("#notice_data-text").val());
	}
	//$("#notice_data-text").val(nickname+' '+$("#notice_data-text").val());
}
function editAddr(i, listname, listvalues) { // fill the form fields in pre for user update
	$("#old_addr_index").val(i);
	$("#new_addr_name").val(listname);
	$("#new_addr_vals").val(listvalues);
}
function delAddr(user_id, i, listname, listvalues) {		 // fill the form fields for user reference after the delete
	$("#old_addr_index").val(i);
	$("#new_addr_name").val(listname);
	$("#new_addr_vals").val(listvalues);
	updateAddr(user_id, true, false);							   // delete the chosen list
}
function showAddrLists(user_id) {
	updateAddr(user_id, false, true);
}
function updateAddr(user_id,dodelete,showfresh) {
	var oldindex = null;
	var listname = 'fresh';
	var listvalues = null;
	if (!showfresh) {
		oldindex = $("#old_addr_index").val();
		listname = $("#new_addr_name").val().replace(/^\s+|\s+$/g,"");
		listvalues = $("#new_addr_vals").val().replace(/^\s+|\s+$/g,"");
	}
	if (!user_id) {
		alert('No user id...');
		return;
	}
	if (!showfresh && (listname == '')) {
		alert('No list name...');
		return;
	}
	if (!showfresh && !dodelete && (listvalues == '')) {
		alert('No list values...');
		return;
	}
	if (!showfresh && (listname.substr(0,1) == '/') || (listname.substr(0,1) == '!') || (listname.substr(0,1) == '@')) {
		alert('Do no prefix the list name with /, ! or @');
		return;
	}
	if (listname.indexOf(' ') > -1) {
		alert('List names may not contain spaces.');
		return;
	}
	if ($("input#token").length) {
		var token = $("input#token").val();
		if (dodelete) listvalues = '-'; // special indication to request delete
		var doshowfresh = (showfresh) ? '&fresh=1' : '';
		var requesturl = getBasePath() + "/list/update/"+user_id+'/addr/'+escape(listname)+'?vals='+escape(listvalues)+doshowfresh+'&token='+token;
		showDiv('working');
		$("#list_workarea").load(requesturl,{},
						function(output) {
								hideDiv('working');
								result = $("#lu_result");
								if (!result) {
									var errmsg = getErrorMsg(output);
									if (errmsg) {
											alert(errmsg);
											return;
									} else {
											alert('ERROR-1: '+output);
											return;
									}
								} else {
							
									//alert("found lu_result");
									if (!$("#lu_status") || !$("#lu_status").get(0)) {
										if (output.indexOf('rc=0') > -1) {
											alert("No change occurred.");
										} else {
											alert("Error-2: "+output);
										}
										return;
									}
									if ($("#lu_status").get(0).tagName.toLowerCase() != 'p') { // make sure it is a <p..> before reference the innerhtml
										alert("Error-3: "+output);
										return;
									}
									if ($("#lu_status").get(0).innerHTML != 'OK') {
										alert("Error-4: "+$("#lu_status").get(0).innerHTML);
										return;
									}
									// remove dl from addr_lists and replace it with the dl from the response
									// both dl's have the same id ...
									var addr_lists = document.getElementById('addr_lists'); // get the div
    							var oldChild = addr_lists.firstChild; 
									while ( oldChild ) {
										if ( (oldChild.tagName != undefined) && (oldChild.tagName.toLowerCase() == "dl") ) {
											addr_lists.removeChild(oldChild);
											break;
										}
										oldChild = oldChild.nextSibling; 
									}
									var newDl = document.getElementById('select_addr_list');
									if (newDl) {
											addr_lists.appendChild(newDl.cloneNode(true));
									}
									var workarea = document.getElementById('list_workarea');
									var maindiv = document.getElementById('lu_result'); // this is already supposed to be pointed to by 'result'
									workarea.removeChild(maindiv);						          // but for some reason node not found (even tho present)
																																		  // attempting removeChild(result) ...
									
									if (showfresh) {
										showDiv('addr_lists');
									} else {
										if (dodelete) {
													$("#ajaxmessage").html(listname+" deleted");
										} else {
													$("#ajaxmessage").html(listname+" saved");
										}
										$("#ajaxmessage").css({display:'none'}); // jwg .. just do it
		              	$("#ajaxmessage").fadeIn(1500);
										setTimeout('fademessage()',2000);
									}										
								}    

					 });
	} else {
		alert("No security token.");
	}
}
function listHelp(which) {
	if (which == 'addr_lists') {
		
			url = getBasePath() + '/help/addr_lists_help.php';
      window.open(url,	'_blank', "toolbar=0,menubar=0,width=320,height=300,scrollbars=1,resizable=1,status=1,location=1");
	
	} else {
		alert("Unexpected listHelp request argument: "+which);
	}
}


function resetPosttos(ops) {
	if (!ops) return; // in case there are no connections setup so no ops present
	var idlist = ops.split(',');
	for (var i=0; i<idlist.length; i++) {		
			var nv = idlist[i].split('=');
			var theid = nv[0];
			var el = $('#'+theid); // theid == 'postto_nn'
			if (el) {
					var nms = new Array(null, 'twitter', 'facebook', null, 'blogspot', 'myspace',
    							 'wordpress', 'tumblr', 'livejournal', 'typepad', 
    							 'linkedin',null,null,null,null,null);	
    			var nm = nms[parseInt(theid.substr(7))];
    			var ptclass = '.postto_network.'+nm;
					var ov = $(ptclass);
					if( nv[1] == 'false' ) {
						el.attr('checked',false);
						ov.removeClass( 'selected' );
					} else {
						el.attr('checked',true);
						ov.addClass( 'selected' );
					}
			}
	}
}

function resetBroadcast() {	 // jwg -- in case it was faded for edit and they changed their mind

	if ($("#notice_post_filter_list")) {
		$("#notice_post_filter_list").fadeTo(1, 1.0);  				// make sure post to options are faded in
	}
}

function saveDraft() {

	$("#notice_update_type").val('save_draft'); // jwg -- 2010-08-26 to distinguish
	$("#isdraft").val('1');
	
	if (!$('#lockbutton').hasClass('selected')) {
		 	$('#lockbutton').addClass('selected');
	}
	document.getElementById('notice_private').checked = true;
	turnOffPostTos();
		
	hideDiv('copy_of_notice');
	$("#form_notice").submit();
}

function doPost() {
	$("#form_notice").submit();
}

// jwg 2010-05-05
function closeUpShop() {
				$( $("#notice_data-text") ).removeClass( 'selected' );

				// jwg 2010-05-05 -- also close attachment area - if open
				if ($("#notice_action-attach_browse").hasClass('display_block')) {
					$("#notice_action-attach_browse").removeClass('display_block');
					$("#notice_action-attach_browse").addClass('display_none');
					$("#notice_action-attach_request").removeClass('attach_close');
					$("#notice_action-attach_request").addClass('attach_open');					
					$("#notice_action-attach_request").blur();
				}
				
				hideDiv('schedule_time');
				
				if ($('#show_post_form').length) {
					hideDiv('form_notice');
					hideDiv('list_shim');
					showDiv('list_shimx');
				}	
				
				$( '#form_notice, #notice_attach_widget, #notice_data-tags' )
					.removeClass( 'activated' );
					
      	if ($("#postto_resets")) { // reset default network target postto selections after post
        	resetPosttos($("#postto_resets").val()); 
      	}					
					
				$("#notice_data-text").val("");
    		$("#notice_data-attach").val("");
    		$("#notice_in-reply-to").val("");
        $('#notice_data-attach_selected').remove();
        $("#notice_data_legend").text($("#notice_legend_text").val()); // jwg 2010-07-09
        
        $("#isdraft").val('0'); // jwg 2010-07-29 make sure the draft setting is turned off
        
        if ($('#uploader_url')) {
        	$('#uploader').attr({src: $('#uploader_url').val()});
        }
        
				$( "#form_notice #notice_data-text" ).focus(); // attempt to re-collapse the area
	
}

// jwg 2010-05-05 
function cancelAction() {
	$("#notice_update_type").val('');	
	$("#notice_update_oldid").val('');	
	$("#notice_data-text").val('');
	resetBroadcast();
	closeUpShop();
	hideDiv('copy_of_notice');
}

/* jwg 2010-08-30 to replace jq onclick */
function lockClicked() {
	var pb = $("#lockbutton");
	if( pb.hasClass( 'selected' )){
		pb.removeClass( 'selected' );
		document.getElementById('notice_private').checked = false;
	} else {
		pb.addClass( 'selected' );
		document.getElementById('notice_private').checked = true;
	}	
}

function showPostForm() {
	showDiv('form_notice');
	showDiv('list_shim');
	hideDiv('list_shimx');
}

// jwg 2009-11-30
function editNotice(notice_id,isPrivate,isDraft) {
	if ($("input#token").length) {
		var token = $("input#token").val();
		$("#notice_update_type").val('edit');
		$("#notice_update_oldid").val(notice_id);
		$("#isdraft").val((isDraft) ? 1 : 0);

		if (!token) { // jwg 2010-06-02
			alert('Note: your session needs to be restored before posting a new notice.\nYou might be able to do this by simply refreshing the page.');
		}
		var requesturl = getBasePath() + "/getnotice/edit/"+notice_id+"/"+token;
		$("#notice_data-text").load(requesturl,{},
						function(output) {
								//alert(output);
								var errmsg = getErrorMsg(output);
								if (errmsg) {
									alert(errmsg);
									return;
								}     
								setPrivacy(isPrivate);
								// jwg 2010-01-30 - for use with notice form on a search results page -- initially not displayed
								if ($("#form_notice") && $("#form_notice").hasClass('display_none')) {
									$("#form_notice").removeClass('display_none');
									$("#form_notice").addClass('display_block');
								}								

								$("#notice_data-text").val(output); // -- if we let the normal course occur we lose newlines -- so stuff it explicitly --
								
								if (!isDraft) { 
									$("#notice_post_filter_list").fadeTo(1, 0.2); // fade it out to imply not available, but keep it there for relative offsets
								}
								
								docountupdate(null);
								window.scroll(0,0); // horizontal and vertical scroll targets
								// jwg 2010-05-05 .. don't show this one now that we have dynamic show of controls
								//$("#ajaxmessage").html("Edit the text. Then click "+buttonValue);
								//$("#ajaxmessage").css({display:'none'}); // jwg .. just do it
                //$("#ajaxmessage").fadeIn(1500);
								//setTimeout('fademessage()',2000);
										
								// jwg 2010-05-05
								showNoticeCtls();
										
								//setTimeout('showCancelEdit()',2000);
					 });
	} else {
		alert("Unauthorized request for data. Please log in.");
	}
}

// jwg 2009-11-30
function resendNotice(notice_id,isPrivate) {
	if ($("input#token").length) {
		var token = $("input#token").val();
		$("#notice_update_type").val('resend');
		$("#notice_update_oldid").val(notice_id);
//		$("#notice_data_legend").text('Discover & Share with the World');
		if (!token) { // jwg 2010-06-02
			alert('Note: your session needs to be restored before posting a new notice.\nYou might be able to do this by simply refreshing the page.');
		}
		var requesturl = getBasePath() + "/getnotice/resend/" + notice_id+"/"+token;
		$("#notice_data-text").load(requesturl,{},
						function(output) {
								//alert(output);
								var errmsg = getErrorMsg(output);
								if (errmsg) {
									alert(errmsg);
									return;
								}           
								$("#notice_data-text").val(output); // -- if we let the normal course occur we lose newlines -- so stuff it explicitly --
								
								if ($("#form_notice") && $("#form_notice").hasClass('display_none')) {
									$("#form_notice").removeClass('display_none');
									$("#form_notice").addClass('display_block');
								}
											
								setPrivacy(isPrivate);

								resetBroadcast(); 
								docountupdate(null);
								window.scroll(0,0); // horizontal and vertical scroll targets
								var buttonValue = $("#notice_update_resend").val(); // get language-specific button name
								if (!buttonValue) {
									alert('missing button value in resendNotice');
									buttonValue = 'Post';
								}
								// jwg 2010-05-05 -- don't show this now that we display controls
								//$("#ajaxmessage").html("Edit the text. Then click "+buttonValue);
								//$("#ajaxmessage").css({display:'none'}); // jwg .. just do it
                //$("#ajaxmessage").fadeIn(1500);
								//setTimeout('fademessage()',2000);
								
								// jwg 2010-05-05
								showNoticeCtls();

								//setTimeout('showCancelResend()',2000);
						});
	} else {
		alert("Unauthorized request for data. Please log in.");
	}
}

// jwg 2010-05-05
function localClicked() {
	var localonly = $('#local_img');	
	if (localonly.hasClass('selected')) {
		localonly.removeClass('selected');
	} else {
		localonly.addClass('selected');
	}
	refreshlci();
}

// jwg 2010-05-05
function consolidateClicked() {
	var consol = $('#consolidate_img');	
	if (consol.hasClass('selected')) {
		consol.removeClass('selected');
	} else {
		consol.addClass('selected');
	}
	refreshlci();
}

// jwg 2010-04-13 - refresh page with updated local,consolidate,ipp value
function refreshlci() 
{
	var uri = document.location.href;
	
	uri = uri.replace(/consolidate=[01]/,'');
	uri = uri.replace(/local=[01]/,'');
	uri = uri.replace(/ipp=\d+/,'');  
	uri = uri.replace(/page=\d+/,'');  // since changes to the others affects page..
	uri = uri.replace(/&&&/g,'&');
	uri = uri.replace(/&&/g,'&');
	uri = uri.replace(/\?\&/,'?');
	uri = uri.replace(/\?$/,'');
	linksub(uri);
}

// jwg 2010-04-05
function linksub(uri) 
{
	if (uri.indexOf('filter=drafts') == -1) { // skip consolidation and local-only if request for drafts 
		var theuri = uri;
		var sep = '?';
		if (theuri.indexOf('?') > -1) sep = '&';
		//var consol = document.getElementById('consolidate');
		var consol = $('#consolidate_img');
		if (consol) {
			//if (consol.checked) {
			if (consol.hasClass('selected')) 
			{
				theuri += sep + 'consolidate=1';
				$('#consolidate').attr('checked',true);
			} else {
				theuri += sep + 'consolidate=0';
				$('#consolidate').attr('checked',false);
			}
			sep = '&';
		}
		//var localonly = document.getElementById('local');
		var localonly = $('#local_img');
		if (localonly) {
			if (localonly.hasClass('selected')) {
			//if (localonly.checked) {
				theuri += sep + 'local=1';
				$('#local').attr('checked',true);
			} else {
				theuri += sep + 'local=0';
				$('#local').attr('checked',false);
			}
			sep = '&';
		}	
		var ipp = document.getElementById('ipp');
		if (ipp) {
			ippval = $("#ipp").val();
			theuri += sep + 'ipp=' + ippval;
			sep = '&';
		}
	}
	document.location.href = theuri;
}

function askNGo(msg,url) {
	if (confirm(msg)) {
		document.location.href = url;
		return;
	} 
}

// jwg 2010-02-26
function setPrivacy(isPrivate) 
{
	document.getElementById('notice_private').checked = isPrivate;
	if (isPrivate) {
		if (!$('#lockbutton').hasClass('selected')) {
			$('#lockbutton').addClass('selected');
		}
	} else {		
		$('#lockbutton').removeClass('selected');
	}
}

// jwg 2010-04-02
function doBlock(elId,submitId) {
	hideDiv(elId);
	$("#"+submitId).submit();  
}

// jwg 2010-03-28
function reportSpam(elId,notice_id,other_notice_id) {

	hideDiv(elId); // hide element containing the calling link
	
	if ($("input#token").length) {
		var token = $("input#token").val();
		
		if (confirm('Do you want to report the selected post as spam?')) { 

			var requesturl = getBasePath() + "/reportspam/"+notice_id+"/?token="+token+"&thenoticeid="+other_notice_id;
			$("#tempwork").load(requesturl,{},
							function(output) {
									var errmsg = getErrorMsg(output);
									if (errmsg) {
										alert(errmsg);
										return;
									}     
									window.scroll(0,0); // horizontal and vertical scroll targets
									$("#ajaxmessage").html(output);
									$("#ajaxmessage").css({display:'none'}); // jwg .. just do it
	                $("#ajaxmessage").fadeIn(1500);
									setTimeout('fademessage()',2000);
						 });
		} else {
									window.scroll(0,0); // horizontal and vertical scroll targets
									$("#ajaxmessage").html('request cancelled');
									$("#ajaxmessage").css({display:'none'}); // jwg .. just do it
	                $("#ajaxmessage").fadeIn(1500);
									setTimeout('fademessage()',2000);
		}
	} else {
		alert("Unauthorized request. Please log in.");
	}
}
							
function removeProfileDiv() {

	if ($('div.profilepopup')) {
		var cells = document.getElementsByTagName("body");   
    var child = cells[0].firstChild; 
		while ( child ) {
			if ( (child.tagName != undefined) && (child.tagName.toLowerCase() == "div") ) {
				if (child.className.match(new RegExp('(\\s|^)'+'profilepopup'+'(\\s|$)'))) {
					cells[0].removeChild(child);
					break;
				}
			}
			child = child.nextSibling;  
		}
	}
}
										
function fademessage()
{
	$("#ajaxmessage").fadeOut(400);
}

// jwg 2009-12-14 -- for use with curvycorners
/*
$(function(){ 
  var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);

  if ($('.global_nav')) {
		//if (browser != "Microsoft Internet Explorer") {	
	  	settings_all = {
	          tl: { radius: 8 },
	          tr: { radius: 8 },
	          bl: { radius: 8 },
	          br: { radius: 8 },
	          antiAlias: true,
	          autoPad: true,
	          validTags: ["div"]
	      	};
	  	$('.global_nav').corner(settings_all);
	  //}
	}
  if ($('.core_area')) {
		//if (browser != "Microsoft Internet Explorer") {
	  	settings_top = {
	          tl: { radius: 8 },
	          tr: { radius: 8 },
	          bl: { radius: 0 },	// make 0 for core against footer, else 8 
	          br: { radius: 0 },  // make 0 for core against footer, else 8
	          antiAlias: true,
	          autoPad: true,
	          validTags: ["div"]
	      }     
  		$('.core_area').corner(settings_top);	  
	  //}
  }
  
  // un-comment for footer against core with rounded bottom corners -- plus related in display.css
  if ($('.footer_nav')) {
		//if (browser != "Microsoft Internet Explorer") {
	  	settings_bot = {
	          tl: { radius: 0 },
	          tr: { radius: 0 },
	          bl: { radius: 8 },
	          br: { radius: 8 },
	          antiAlias: true,
	          autoPad: true,
	          validTags: ["div"]
	      }        
  		$('.footer_nav').corner(settings_bot);
  	//}
  }
  });
*/


// jwg 2009-12-01
function getErrorMsg(output) {	// process std error.php output to get error message
            	if (output.indexOf('body id="error"') > 0) {
            			x = output.indexOf('class="error"');
            			if (x > 0) {
            				x = output.indexOf('>',x);
            				y = output.indexOf('<',x+1);
            				return output.substr(x+1, y-(x+1));
            			} else {
            				return "an error occured.";
            			}	
            	} else if (output.indexOf(' id="error"') > 0) {
            			x = output.indexOf(' id="error"');
            		 	x = output.indexOf('>',x);
            			y = output.indexOf('<',x+1);
            			return output.substr(x+1, y-(x+1));
            	} else {
									return null;
							}
}	

// jwg 2009-12-01
function getCurrentDomain() {
	  var href = window.location.href;
	  var x = 0;
	  if (href.substr(0,7) == 'http://')  {
	  	x = 7;
	  } else if (href.substr(0,8) == 'https://') {
	  	x = 8;
	  }
	  if (x == 0) return '';
	  y = href.indexOf('/', x);
	  if (y > -1) {
	  	return href.substr(x, y-x);
	  } else {
    	return href.substr(x);
  	}
}
function getBasePath() {
	  var href = window.location.href;
	  var x = 0;
	  if (href.substr(0,7) == 'http://')  {
	  	x = 7;
	  } else if (href.substr(0,8) == 'https://') {
	  	x = 8;
	  }
	  if (x == 0) return '';
	  y = href.indexOf('/', x);
	  if (y > -1) {
	  	return href.substr(0, y);
	  } else {
    	return href.substr(0);
  	}
}

function docountupdate(event) {

		if (!$("#notice_data-text")) return; // jwg 2010-04-28
		
		var maxLength = 10000;	// jwg 2010-01-24 -- was 140 for direct messages .. now 1000 [ 10000 as of 2-20, but not chgd here til 3-24 ]
		var submit_button = document.getElementById('notice_action-submit');
		if (!submit_button) {
				submit_button = document.getElementById('notice_action-submit_tab2');	// new tab submit button
		}
		if (submit_button && (submit_button.name == 'status_submit'))
			maxLength = 10000;	
		if (event) {
			if (event.keyCode == 8) { // backspace
				var textel = $("#notice_data-text");
				var currentLength = textel.val().length; // get apparent length (seems to be old length...)
				while ((currentLength > 0) && ((textel.val().substr(currentLength-1,1) == ' ') || (textel.val().substr(currentLength-1,1) == null))) {
					currentLength--;
				}
				counterused = $("#notice_text-countused");	// jwg 2009-09-20 -- added used characters counter in notice display
				if (counterused) {
					if (currentLength == 0) {
						counterused.text(addcommas(maxLength));
					} else {
						counterused.text(addcommas(currentLength));
					}
				}
	
				return;
			}
		}
		var currentLength = 0;
		var remaining = 0;
		var counter = null;
		if (document.getElementById('form_notice')) { // jwg .. added conditional in order to use function when no notice area in page
			currentLength = $("#notice_data-text").val().length;
			remaining = maxLength - currentLength;
			counterused = $("#notice_text-countused");	// jwg 2009-09-20 -- added used characters counter in notice display
			if (counterused) {
				if (currentLength == 0) {
					counterused.text(addcommas(maxLength));
				} else {
					counterused.text(addcommas(currentLength));
				}
				//counterused.text(currentLength);
			}
			

			counter = $("#notice_text-count");
			if (counter) {
				counter.text(addcommas(remaining));
				//counter.text(remaining);
			}
			if (remaining < 0) {
				$("#form_notice").addClass("warning");
				var noticestr = $("#notice_data-text").val();
				$("#notice_data-text").val(noticestr.substr(0,maxLength));
				alert("Maximum message length has been reached.");
				docountupdate(); // call self to reset counters, e.g. to 0
			} else {
				$("#form_notice").removeClass("warning");
			}
	
		}
		

// jwg 2009-10-26 -- remove the counter, since we now allow 10,000 bytes for bio ...
//		// jwg -- add counter to bio in registration and edit profile settings -- piggy back on this function -- 2009-08-25
//		if (document.getElementById('form_settings_profile') || document.getElementById('form_register')) {
//			currentLength = $("#bio").val().length;
//			remaining = maxLength - currentLength;
//			counter = $("#bio-count");
//			counter.text(remaining);
//		}				
}

	function addcommas(num) {
		var strnum = num + '';
		var outnum = '';
		var tripctr = 0;
		for (var i=strnum.length-1; i >= 0; i--) {
				outnum = strnum.substr(i,1) + outnum.toString();
				tripctr++;
				if ((i > 0) && (tripctr >= 3)) {
					outnum = ',' + outnum;
					tripctr = 0;
				}				
		}
		return outnum;
	}

function SetCookie( name, value, days, domain )
{
    var expires = "";
    if( value == null ) {
    		//alert("SetCookie " + name + " to null."); // DEBUG
        days = -1;
    }
    
    if( days && days > 0 )
    {
        //alert("SetCookie " + name + "=" + value + " w/ days=" + days); // DEBUG 
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else if( days && days == -1 )
    {
        expires = "; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
    else if( !days )
    {
        expires = "; expires=Mon, 01-Jan-2024 00:00:01 GMT";
    } 
    
    var dom = 'domain=' + domain + ';";';
    var href = window.location.href;
    if (href.indexOf('localhost/') > -1)
    	dom = '';
    
    document.cookie = name+"="+escape(value)+expires+"; path=/; " + dom;  
}

function GetCookie( name )
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for( var i=0; i < ca.length; ++i )
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
    }
    return '';
}

function popUpProperties(inobj) {
	op = window.open();
	op.document.open('text/plain');
	for (objprop in inobj) {
	op.document.write(objprop + ' => ' + inobj[objprop] + '\n');
	}
	op.document.close();
}

function getCursorPosition (ctrl) {
	var CursorPos = 0;	// IE Support
	if (document.selection) {
		ctrl.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart ('character', -ctrl.value.length);
		CursorPos = Sel.text.length;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
		CursorPos = ctrl.selectionStart;
	}
	return (CursorPos);
}

function setCursorPosition(node,pos){ 
 
    var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node; 
    if(!node){ 
        return false; 
    }else if(node.createTextRange){ 
        var textRange = node.createTextRange(); 
        textRange.collapse(true);  
        textRange.moveStart('character',pos); 
        textRange.moveEnd('character',pos);
        //textRange.select(); 
        return true; 
    }else if(node.setSelectionRange){
        node.setSelectionRange(pos,pos); 
        return true; 
    } else {
    	//alert("unknown type");
    }
 
    return false; 
} 

// jwg 2010-02-17
function selectSection() {
		var sel = document.getElementById('section_selector');
		document.location.href = sel[sel.selectedIndex].value;
}

// jwg 2010-04-02
function showImage(imgEl, imgName) {
		imgEl.src = getBasePath() + '/images/' + imgName;
}

// jwg 2010-04-05
function dosearch(uri, promptmsg, newwindow) 
{
	var q = prompt(promptmsg, '');
	if (!q) return;	

	if (newwindow) {
     window.open(uri + q,	'_blank', "toolbar=1,menubar=1,width=1024,height=600,scrollbars=1,resizable=1,status=1,location=1");
     return false;		
	} else {
		document.location.href = uri + escape(q);
	} 
}

/* now that we are not dealing with sliding sections ... drop this

	// jwg 2010-02-15
	function selectSection(nickname) {
		var sel = document.getElementById('section_selector');
		var section = sel[sel.selectedIndex].value;
		switch (section) {
			case '0': 
				setLocalSection(nickname);
				break;
			case '1':
				setTwitterSection(nickname);
				break;
			default:
		}
	}

	// jwg 2010-02-15
	function setLocalSection(nickname) {
		var lsb = $("#local_section_body");
		if (lsb.hasClass('display_block')) return;
		if ($("#twitter_section_body")) { close_section(null,$("#twitter_section_body")); }
		$active = $('.subbar_active', lsb);
		if ($active) {
			$active.removeClass('subbar_active');
			$active.addClass('subbar_inactive');
		}
		open_section(null, lsb);
		SetCookie('open_section', 'local', null, getCurrentDomain());
		loadpage('all',nickname);
	}
	
	// jwg 2010-02-15
	function setTwitterSection(nickname) {
		var tsb = $("#twitter_section_body");
		if (tsb.hasClass('display_block')) return;
		if ($("#local_section_body")) { close_section(null,$("#local_section_body")); }
		$active = $('.subbar_active', tsb);
		if ($active) {
			$active.removeClass('subbar_active');
			$active.addClass('subbar_inactive');
		}
		open_section(null, tsb);
		SetCookie('open_section', 'twitter', null, getCurrentDomain());
		loadpage('all/twitter',nickname);
	}
	
	// jwg 2010-02-03
	function open_section(section_header, section_body) {
		if (section_body) {
			if (section_body.hasClass('display_none')) {
				section_body.removeClass('display_none');
			}
			section_body.addClass('display_block');
		}
	}
	// jwg 2010-02-03
	function close_section(section_header, section_body) {
		if (section_body) {
			if (section_body.hasClass('display_block')) {
				section_body.removeClass('display_block');
			}
			section_body.addClass('display_none');
		}
	}	
	
	function loadpage(path,nickname,alt) {
		var uri = getBasePath() + '/';
		if (nickname == '') {
			document.location.href = uri + alt;
			return; 
		} else {		
			var cururi = document.location.href;
			var curpath = cururi.substr(uri.length);
			var x = curpath.indexOf('/');
			if (x == -1) x = curpath.length - 1; 
			var pathpart = curpath.substr(0,x+1);	// assuming this is the username, since loadpage should ONLY BE CALLED in Home context 
			if (pathpart.substr(pathpart.length-1,1) != '/') pathpart = pathpart + '/';
			if (pathpart.indexOf(nickname) == -1) {
				pathpart = pathpart + nickname + '/';
			}
			document.location.href = getBasePath() + '/' + pathpart + path;
		}
	}
*/

/* ... looped...
var MAX_DUMP_DEPTH = 10;
       
       function dumpObj(obj, name, indent, depth) {
              if (depth > MAX_DUMP_DEPTH) {
                     return indent + name + ": <Maximum Depth Reached>\n";
              }
              if (typeof obj == "object") {
                     var child = null;
                     var output = indent + name + "\n";
                     indent += "\t";
                     for (var item in obj)
                     {
                           try {
                                  child = obj[item];
                           } catch (e) {
                                  child = "<Unable to Evaluate>";
                           }
                           if (typeof child == "object") {
                                  output += dumpObj(child, item, indent, depth + 1);
                           } else {
                                  output += indent + item + ": " + child + "\n";
                           }
                     }
                     return output;
              } else {
                     return obj;
              }
       }
*/

/* 2010.05.04 KJD: Added */
$().mousemove(function(e){
   // e.pageX - gives you X position
   // e.pageY - gives you Y position
});

var isOver	= false;

// jwg 2010-06-02
function newdoodle() {
	var test_canvas = document.createElement("canvas");
	if (!test_canvas.getContext) {
		showDiv('browser_not_supported');
	} else {
		var dwin = window.open('/extlib/mrdoob-harmony/src/index.html','doodles','toolbar=0,location=0,directories=0,status=1,menubar=0,resizable=1,width=300,height=300,left=0,top=300');
	}
}

// jwg 2010-06-05
function followedtwlists(user_id) {
	if (!user_id) {
		alert("No user id. Login and try again.");
		return;
	}
	var token = $("input#token").val();
	if (!token) {
		alert("No session token. Refresh page and try again.");
		return;
	} 
	var twlister = getBasePath()+'/followedtwlists/'+user_id+'/'+token;
	//var tlwin = window.open(twlister, 'TwitterLists', 'top=50,left=10,width=560,height=150,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0');
	$("#the_lists_list").load(twlister,{},
						function(output) {
								var errmsg = getErrorMsg(output);
								if (errmsg) {
									alert(errmsg);
									return;
								}  
						}
	);	
	showDiv('lists_list');
}

function showTwList(listuri) {
	var twlisturl = 'http://twitter.com'+listuri
	var twlist = window.open(twlisturl, 'TwitterList', 'top=300,left=10,width=760,height=400,toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1');
	twlist.focus();
}

/* jwg 2010-07-15 -- use alt approach
// jwg 2010-06-24 from marc ------------------------------------
function popVideo(vid,vidURL) {

	if (typeof(vid)=="string") { vid=document.getElementById(vid); vidURL=document.getElementById(vidURL); }
	if (vid&&typeof(vid)=="object") {
	// Make the video visible and set the zindex so its on top of everything else

	vid.style.zIndex='100'; 
	vid.style.display='block';
	vidURL.style.display='none';
	var scrollTop = 0;
	if (document.documentElement && document.documentElement.scrollTop){
		scrollTop = document.documentElement.scrollTop;
	} else if (document.body){
		scrollTop = document.body.scrollTop;
	}
	// set the starting x and y position of the video
	vid.style.top=scrollTop+Math.floor((document.documentElement.clientHeight/2)-(vid.offsetHeight/2))+'px';
	vid.style.left=Math.floor((document.documentElement.clientWidth/2)-(vid.offsetWidth/2))+'px';
	}
return false;
}

function closeVideo(vid,vidURL) {

	if (typeof(vid)=="string") { vid=document.getElementById(vid);vidURL=document.getElementById(vidURL); }
	if (vid&&typeof(vid)=="object") {
	// Hide the video 

	vid.style.zIndex='100'; 
	vid.style.display='none';
	vidURL.style.display="block";
	var scrollTop = 0;
	if (document.documentElement && document.documentElement.scrollTop){
		scrollTop = document.documentElement.scrollTop;
	} else if (document.body){
		scrollTop = document.body.scrollTop;
	}
	// set the starting x and y position of the video
	vid.style.top=scrollTop+Math.floor((document.documentElement.clientHeight/2)-(vid.offsetHeight/2))+'px';
	vid.style.left=Math.floor((document.documentElement.clientWidth/2)-(vid.offsetWidth/2))+'px';
	}
return false;
}
*/

/*
// Marc Quinlivan
function letternumber()
{
	if (event.shiftKey)  // Check For Shift Key Press
	{
		if ( event.keyCode >=65 && event.keyCode <=90) // Check for keys A-Z. We only want to accept keys a-z with the SHIFT key (upper case)
		{
			event.cancelBubble = false;
			event.returnValue = true;
		}	else {
			event.cancelBubble = true;
			event.returnValue = false;
		 }
	}
	else if (event.ctrlKey)  // check for control key press
	{
		if ( event.keyCode == 67 || event.keyCode == 86 || event.keyCode == 88 )	// Check for C, X, or V. We only want to accept copy\cut\paste
		{
			event.cancelBubble = false;
			event.returnValue = true;
		}	else {
			event.cancelBubble = true;
			event.returnValue = false;
		}
	}
	else if ( (event.keyCode >=48 && event.keyCode <=58) || (event.keyCode >=65 && event.keyCode <=90) || (event.keyCode >=96 && event.keyCode <=105) || (event.keyCode == 46) || (event.keyCode >=35 && event.keyCode <=40) || (event.keyCode == 8) || (event.keyCode == 9)) // check for a-z. 0-9 (top row), 0-9 (number pad), DEL, cursor keys, backspace, tab. This is all we want to accept.
	{
		event.cancelBubble = false;
		event.returnValue = true;
	}
	else {
		event.cancelBubble = true;
		event.returnValue = false;
	}
}
*/