function popup(url) {
  var newwindow = window.open(url,'name','height=400,width=600');
  if (window.focus) newwindow.focus();
  return false;
}

function collapse(id) { $('#'+id).slideToggle(); }
function fade(id,value) { if(value>0) $('#'+id).hide().fadeIn('slow'); else $('#'+id).show().fadeOut('slow'); }
function ajax(u,s,t) {
  var query="";
  for(i=0; i<s.length; i++) { 
     if(i>0) query=query+"&";
     query=query+encodeURIComponent(s[i])+"="+encodeURIComponent(document.getElementById(s[i]).value);
  }
  $.ajax({type: "POST", url: u, data: query, success: function(msg) { document.getElementById(t).innerHTML=msg;  } });  
}
String.prototype.reverse = function () { return this.split('').reverse().join('');};
$(document).ready(function() {
$('.hidden').hide();
$('.poke').hide().slideDown('slow');
$('.error').hide().slideDown('slow');
$('.success').hide().slideDown('slow');
$('.flash').click(function() { $(this).fadeOut('slow'); return false; });
$('input.string').attr('size',50);
$('input.integer').keyup(function(){this.value=this.value.reverse().replace(/[^0-9\-]|\-(?=.)/g,'').reverse();});
$('input.double').keyup(function(){this.value=this.value.reverse().replace(/[^0-9\-\.]|[\-](?=.)|[\.](?=[0-9]*[\.])/g,'').reverse();});
$('input.delete').attr('onclick','if(this.checked) if(!confirm("Sure you want to delete this object?")) this.checked=false;');
try {$("input.date").focus( function() {Calendar.setup({
     inputField:this.id, ifFormat:"%Y-%m-%d", showsTime:false
}); }); } catch(e) {};
try { $("input.datetime").focus( function() {Calendar.setup({
     inputField:this.id, ifFormat:"%Y-%m-%d %H:%M:%S", showsTime: true,timeFormat: "24"
}); }); } catch(e) {};
try { $("input.time").clockpick({
     starthour:0, endhour:23, showminutes:true, military:true
}); } catch(e) {};
});

var nicButtonList = ['bold', 'italic', 'underline', 'left', 'center',
                     'right', 'justify', 'ol', 'ul', 'subscript', 'superscript',
                     'strikethrough', 'removeformat', 'hr', 'forecolor',
                     'bgcolor', 'link', 'unlink', 'fontSize', 'fontFamily',]
		        
var nicIconsPath = '/jwfind/static/nicEditorIcons.gif'

var myNicEd = null
function myNic()
{
	if (myNicEd == null)
	  myNicEd = new nicEditor(
		    {
		    	buttonList : nicButtonList, 
		      	iconsPath : nicIconsPath
		    });
	return myNicEd;
}
function insert(text, instance)
{
    if (instance == parseInt(instance))
    {
        instance = parseInt(instance);
        ed = nicEditors.editors[0].nicInstances[instance];
        content = ed.getContent() + text
        ed.setContent(content);
    }
    else
    {
        element = document.getElementById(instance);
        element.value += text
    }
}   
function insert_bible_verse(instance)
{
    verse = document.getElementById('verse'+instance).value;
    book = document.getElementById('book'+instance).value;
    chapter = document.getElementById('chapter'+instance).value;
    
    if (verse > 0 && verse < 180 && chapter > 0 && chapter < 180)
        insert("(" + book + " " + chapter + ":" + verse + ")",instance);
    else
        alert("sorry, bad chapter or verse");
}   

function stationery_select(val, field) {
 document.getElementById(field).value=val;
}

function stationery_myajax(u,f) {
  $.ajax({type: "POST", url: u, data: 'field='+f, success: function(msg) {
    document.getElementById('stationery_selection').innerHTML=''; 
    seltd = document.getElementById(f).parentNode;
    seltd.innerHTML = seltd.innerHTML + msg; 
  } });
}

function show_ajaxbar() {
	$("html").css("overflow", "hidden");
	el=document.getElementById('ajaxbar') 
	el.style.display='table-cell';
}
function hide_ajaxbar() {
	$("html").css("overflow", "auto");
	el=document.getElementById('ajaxbar') 
	el.style.display='none';
}
function myajax(u,d,t) {
	show_ajaxbar();
	$.ajax({type: "POST", url: u, data: d, success: function(msg) { 
		if (t != '') 
			document.getElementById(t).innerHTML=msg;
		hide_ajaxbar();
	} 
	});
}
function persact_myajax(funct, uid) {
  myajax('/jwfind/users_ajax/'+funct,'uid='+uid,'action_bar_'+uid);
  myajax('/jwfind/users_ajax/refresh_picto','uid='+uid,'picto_bar_'+uid);
}

function nick_suggestions()
{
	nick = escape(encodeURI(document.getElementById('nick').value));
	if (nick.length > 2)
		myajax('/jwfind/public_ajax/nick_suggestions','nick='+nick,'nick_suggestions');
	else
		document.getElementById('nick_suggestions').innerHTML = '';
}

function updates_before(before, iter)
{
	//document.getElementById('before').id = 'before_old' 
	myajax('/jwfind/users_ajax/updates_before','before='+before+'&iter='+iter,'before_'+iter);
}

function mmail_recipients_ajax(type) {
  myajax('/jwfind/admins_ajax/massmail_select','type='+type,'mmsel');
}

function mmail_recipients_param_ajax(type) {
	param = prompt(type);
	if (param)
		myajax('/jwfind/admins_ajax/massmail_select','type='+type+'&param='+param,'mmsel');
}

//deprecated
function wall_ajax(fc, id, context) {
  myajax('/jwfind/'+fc,'id='+id+'&context='+context,'wall_'+id);
}

function comment_ajax(person_id,media_type,media_id,comment_id,reply,body) {
  if (body == '1')
    body_text = escape(encodeURI(document.getElementById('comment_body').value));
  else if (body == 'remove')
	body_text = 'remove_comment'
  else
	body_text = '';
  if (typeof instance == 'undefined')
	instance = 0;
  $.ajax({type: "POST", url: '/jwfind/users_ajax/comment', data: 'person_id='+person_id+'&media_type='+media_type+'&media_id='+media_id+'&comment_id='+comment_id+'&reply='+reply+'&body='+body_text, success: function(msg) { 
	  document.getElementById('comments_'+media_type+'_'+media_id).innerHTML=msg; 
	  myNicEd = myNic();
	  nicEditors.editors[instance].nicInstances = new Array();
	  ed = myNicEd.panelInstance('comment_body'); 
	  nicEditors.editors[instance].nicInstances[0].focus();
	  } });
}

function toggle_visibility(elem)
{
	e = document.getElementById(elem);
	alert(e.style.display)
	if(e.style.display == 'none')
       e.style.display = 'block';
    else
       e.style.display = 'none';
}

function show_comments(id)
{
	document.getElementById('commentsshow_'+id).style.display = 'none';
	document.getElementById('commentscontent_'+id).style.display = 'block';
	document.getElementById('commentshide_'+id).style.display = 'inline';
}

function hide_comments(id)
{
	document.getElementById('commentsshow_'+id).style.display = 'inline';
	document.getElementById('commentscontent_'+id).style.display = 'none';
	document.getElementById('commentshide_'+id).style.display = 'none';
	document.getElementById('comments_help').style.display = 'none';
	document.getElementById('comments_help_button').style.display = 'inline';
}
function show_comments_help() {
	myajax('/jwfind/rcadmin/ares_es_ajax', '', 'comments_help');
	//myajax('/jwfind/public_ajax/comments_help','','comments_help');
	document.getElementById('comments_help').style.display = 'block';
	document.getElementById('comments_help_button').style.display = 'none';
}
function user_note(id, name, message)
{
	mess = prompt('comment on '+name+'\'s registration, verification or approval:',message);
	if (mess) {
		mess = escape(encodeURI(mess))
		myajax('/jwfind/admins_ajax/user_note','id='+id+'&message='+mess,'note_on_'+id);
	}
}

//CHAT
function keypressed(e)
{
  var keynum;
  var keychar;
  var numcheck;
  if(window.event) { // IE
    keynum = e.keyCode;
  }
  else if(e.which) { // Netscape/Firefox/Opera
    keynum = e.which;
  }
  keychar = String.fromCharCode(keynum);
  alert(keychar);
}

function chat_invite_poke(roomid, nick) {
	  myajax('/jwfind/users_ajax/chat_invite_poke','nick='+nick+'&roomid='+roomid,'');
}

function chat_add_nick(nick)
{
	insert(nick+': ', 'ptext')
	el_ptext =  document.getElementById('ptext');
	el_ptext.focus();
}

function chat_insert_post(id, name, post, posted, system, color)
{
	if (system)
	{
		el_parent = document.getElementById('system');
		newtd_name = document.createTextNode('');
		max = 4;
	}
	else
	{
		el_parent = document.getElementById('posts');
		newtd_name = document.createElement('td');				
		newtd_name_s = document.createElement('strong');
		newtd_name_s_a = document.createElement('a');
		newtd_name_s_a.setAttribute('href', 'javascript:chat_add_nick("'+name+'");');
		if (color != null & color != '')  
			newtd_name_s_a.setAttribute('style', 'color:#'+color+';'); 
		newtd_name_s_a.innerHTML = name + ":";
		newtd_name.appendChild(newtd_name_s);
		newtd_name_s.appendChild(newtd_name_s_a);
		max = 13;
	}

	newtr = document.createElement('tr');
	newtr.setAttribute('id', 'p_'+id);
	
	newtd_at = document.createElement('td');
	newtd_at.setAttribute('style', "text-align:right;");
	newtd_at.innerHTML = posted;
	newtr.appendChild(newtd_at);

	newtr.appendChild(newtd_name);

	newtd_post = document.createElement('td');
	newtd_post.innerHTML = post;
	newtr.appendChild(newtd_post);
	
	el_parent.appendChild(newtr);
	
	if (el_parent.childNodes.length > max)
		el_parent.removeChild(el_parent.firstChild);				
}

function chat_process_response_msg(msg)
{
  var resp = eval('(' + msg + ')');
  if (resp.chat.highpost != null) 
	el_highpost.value = resp.chat.highpost;
  if (resp.chat.buddies != null)
  {
	  if (resp.chat.buddies == '<b>kicked!</b>')
	  {
		  window.alert('You have been kicked!');
		  window.location="http://www.jwfind.net/jwfind/public/kicked";
	  }
	  else
	  {
	      el_bud = document.getElementById("buddies");
	      el_bud.innerHTML = resp.chat.buddies;
	  }
  }
  if (resp.chat.posts != null)
  {
	for(i=0; i < resp.chat.posts.length; i++) {
		p = resp.chat.posts[i];
		already = document.getElementById("p_"+p.id);
		if (already == null)
		{
			already = document.getElementById("p_"+p.timestamp);
			if (already != null)
			{
				already.parentNode.removeChild(already);
			}
			chat_insert_post(p.id, p.name, p.post, p.posted, p.system, p.color);
		}
	}
  }
  if ((resp.chat.message != null) & (resp.chat.message != ''))
  	//window.status = resp.chat.message;
	chat_insert_post(0, 'system', resp.chat.message, '', false, null);
}

function chat_handle_newposts_ajax()
{
  el_room_id = document.getElementById('room_id');
  el_highpost = document.getElementById('highpost');
  u = '/jwfind/users_ajax/chat_newposts';
  query = 'highpost='+el_highpost.value+'&room_id='+el_room_id.value;
  $.ajax({type: "POST", url: u, data: query, success: function(msg) {
	  chat_process_response_msg(msg);
  } });  
}

function chat_kick_user(room_id, nick) {
	$.ajax({type: "POST", url: '/jwfind/users_ajax/chat_kick_user', data: 'room_id='+room_id+'&nick='+nick, success: function(msg) {
	  	window.status = msg;
	} });  
}

function chat_kick_revoke(room_id, nick) {
	$.ajax({type: "POST", url: '/jwfind/users_ajax/chat_kick_revoke', data: 'room_id='+room_id+'&nick='+nick, success: function(msg) {
	  	window.status = msg;
	} });  
}

function chat_say_sorry(nick) {
	insert("Sorry "+nick+"! I'll correct myself.", 'ptext')
	el_ptext =  document.getElementById('ptext');
	el_ptext.focus();	
}

function chat_post_ajax() {
	el_ptext = document.getElementById('ptext');
	ptext_plain = html_sanitize(el_ptext.value);
	ptext = escape(encodeURIComponent(el_ptext.value));
	el_ptext.value = '';
	room_id = document.getElementById('room_id').value;
	u = '/jwfind/users_ajax/chat_post';
    el_highpost = document.getElementById('highpost');
    timestamp= new Date().getTime();
    nick = document.getElementById('user_nick').value;
    chat_insert_post(timestamp, nick, ptext_plain, 'now', false, null)
	query = 'highpost='+el_highpost.value+'&room_id='+room_id+'&ptext='+ptext+'&timestamp='+timestamp;
    $.ajax({type: "POST", url: u, data: query, success: function(msg) {
  	  chat_process_response_msg(msg);
    } });  
}

//function poolanswer_ajax(pool, answer) {
//	myajax('/jwfind/users_ajax/pool_answer','pool='+pool+'&answer='+answer,'pool');
//}

function pool_answer(pool, answer) {
	window.location = '/jwfind/users/pool_answer?pool='+pool+'&answer='+answer;
}

function pool_plot_old(data) {
	var g = new Bluff.Pie('pool_plot', 276);
	g.set_theme({
	    colors: ['#185360', '#2999b2', '#d1d9da'],
	    marker_color: '#585858',
	    font_color: '#585858',
	    background_colors: ['#fafafa', '#fafafa']
	});
	g.legend_font_size = 40; 
	g.marker_font_size = 40;
	for (i in data.items) {
	    var item = data.items[i];
	    g.data(item.label, item.data);
	}
	g.draw();
}

function confirm_loc(msg, url) {
	if (confirm(msg))
	{
		window.location = url;
	}
}
function promptBeforeDeleting(oldLink) {
	if (confirm("Really delete?"))
	{
		window.location = oldLink;
	}
}
function promptBeforeExiting(oldLink) {
	if (confirm("Exit without saving?"))
	{
		window.location = oldLink;
	}
}
function switchLinks(d) {
	var oldLink="";
	for (var i=0; i < d.links.length; i++)
	{
		oldLink = d.links[i].href;
		if (oldLink.substring(0,10) != 'javascript')
			d.links[i].href = "javascript: promptBeforeExiting('"+ oldLink + "')";
	}
}

function init_google_websearch(theterm) {
	var searchControl = new google.search.SearchControl();
	var siteSearch = new google.search.WebSearch()
	siteSearch.setUserDefinedLabel("JWFind.net contents");
	siteSearch.setUserDefinedClassSuffix("siteSearch");
	siteSearch.setSiteRestriction("www.jwfind.net");
	var options = new google.search.SearcherOptions();
	options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
	searchControl.addSearcher(siteSearch, options);
	searchControl.draw(document.getElementById("searchcontrol"));
	searchControl.execute(theterm);
}
function guppy(id) {
	el_input = document.getElementById('guppy_input_' + id);
	code = escape(encodeURI(el_input.value));
    myajax('/jwfind/admins_ajax/guppy','id='+id+'&code='+code, 'guppy_' + id);
}
function open_pokereply(poid,type) {
	el_bar = document.getElementById(type+'reply_box_' + poid);
	el_action_bar = document.getElementById(type+'reply_open_' + poid);
	el_bar.style.display = 'block';
	el_action_bar.style.display = 'none';
}
function pokereply(poid,type) {
	el_box = document.getElementById(type+'reply_' + poid);
	body = escape(encodeURI(el_box.value));
    myajax('/jwfind/users_ajax/send_'+type+'reply','poid='+poid+'&body='+body, type+'_'+poid);
}
function open_interaction_bar(uid,type) {
	el_bar = document.getElementById(type+'_bar_' + uid);
	el_action_bar = document.getElementById('action_bar_' + uid);
	el_bar.style.display = 'block';
	el_action_bar.style.display = 'none';
}
function close_interaction_bar(uid,type) {
	el_bar = document.getElementById(type+'_bar_' + uid);
	el_action_bar = document.getElementById('action_bar_' + uid);
	el_bar.style.display = 'none';
	el_action_bar.style.display = 'block';
}
function interact(uid,type) {
	el_box = document.getElementById(type+'_box_' + uid);
	body = escape(encodeURI(el_box.value));
	el_result = document.getElementById('action_result_' + uid);
	if (el_result != null)
	{
		el_result.style.display = 'none';
	}
    myajax('/jwfind/users_ajax/send_'+type,'uid='+uid+'&body='+body,'action_bar_'+uid);
    close_interaction_bar(uid,type)
}
function get_radio_value(radioObj) {
	if(!radioObj)
		return "";
	children = radioObj.childNodes
	var radioLength = children.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(children[i].checked) {
			return children[i].value;
		}
	}
	return "";
}
function quick_post_focus() {
    el_res = document.getElementById('quickpost_result');
	el_actbar = document.getElementById('quickpost_actionbar');
	el_menu = document.getElementById('quickpost_menu');
	el_area = document.getElementById('quickpost_textarea');
	
	el_actbar.style.display = 'block';
	el_menu.style.display = 'block';
	el_area.style.height = '100px';
    el_res.style.display = 'none';
	
	if ((el_area.value == "Share what's on your mind..") || (el_area.value == "Share something else.."))
		el_area.value = '';
}
function quick_post_send() {
    el_res = document.getElementById('quickpost_result');
	el_menu = document.getElementById('quickpost_menu');
	el_radio = document.getElementById('quickpost_permission');
	el_area = document.getElementById('quickpost_textarea');
	el_actbar = document.getElementById('quickpost_actionbar');
	
	perm = get_radio_value(el_radio);
	body = escape(encodeURI(el_area.value));
	el_actbar.style.display = 'none';
    el_res.style.display = 'none';
	
    $.ajax({type: "POST", url: '/jwfind/users_ajax/quick_blog', data: 'perm='+perm+'&body='+body, success: function(msg) {
    	el_res.innerHTML = msg;
    	el_res.style.display = 'block';
    	result = msg.substring(12,17);
    	if (result == 'error')
    	{
    		el_actbar.style.display = 'block';
    	}
    	else
    	{
    		el_area.style.height = '30px';
    		el_area.value = "Share something else..";
    		el_menu.style.display = 'none';
    	}
    } });
}
function contact_picupload_hide() {
	el_p2r = document.getElementById('message_picture_2');
	el_p2r.style.display = 'none';
	el_p3r = document.getElementById('message_picture_3');
	el_p3r.style.display = 'none';
	el_p4r = document.getElementById('message_picture_4');
	el_p4r.style.display = 'none';
	function p1el_change() { el_p2r.style.display = 'inline'; }
	function p2el_change() { el_p3r.style.display = 'inline'; }
	function p3el_change() { el_p4r.style.display = 'inline'; }	
	el_p1l = document.getElementById('message_picture_1');
	el_p1l.onchange = p1el_change;
	el_p2l = document.getElementById('message_picture_2');
	el_p2l.onchange = p2el_change;
	el_p3l = document.getElementById('message_picture_3');
	el_p3l.onchange = p3el_change;
}
function request_note(id, message)
{
	mess = prompt('Attach note to request #'+id+':', message);
	if (mess) {
		mess = escape(encodeURI(mess))
		myajax('/jwfind/admins_ajax/request_solved','id='+id+'&solved=0&message='+mess,'req_note_'+id);
	}
}
function request_solved(id, message)
{
	mess = prompt('Set request #'+id+' as solved and attach note:', message);
	if (mess) {
		mess = escape(encodeURI(mess))
		myajax('/jwfind/admins_ajax/request_solved','id='+id+'&solved=1&message='+mess,'req_note_'+id);
		actb = document.getElementById('req_action_'+id);
		actb.innerHTML='<i>.. solved</i>';
		//tr = document.getElementById('req_'+id);
		//tr.parentNode.removeChild(tr);
	}
}
function show_section(group)
{
	var sections = ["basic", "spiritual", "physical", "passions", "location", "skills", "ALL", "contacts"];
	for (var i=0; i < sections.length; i++)
	{
		el_sec = document.getElementById('profile_content_' + sections[i]);
		el_menu = document.getElementById('profile_menu_' + sections[i]);
		if (el_sec != null)
		{
			if (sections[i] == group)
			{
				el_sec.style.display = 'block';
				//el_menu.style.background = '#fff';
				el_menu.className = 'active';
			}
			else
			{
				el_sec.style.display = 'none';
				//el_menu.style.background = '#E1E1E1';
				el_menu.className = 'inactive';
			}
		}
	}
}
function select_language(lang)
{
	myajax('/jwfind/users_ajax/select_language','lang='+lang,'language');
}

function toggle_smiley_palette(instance)
{
    el_main = document.getElementById('smh_main_'+instance);
    el_cust = document.getElementById('smh_custom_'+instance);
    el_toggler = document.getElementById('smh_toggler_'+instance);
	basic = el_cust.style.display == 'none'
    
    if (basic)
    {
        el_main.style.display = "none";
        el_cust.style.display = "inline";
        el_toggler.innerHTML='basic palette..';
        //basic = false;
    }
    else
    {
        el_main.style.display = "inline";
        el_cust.style.display = "none";
        el_toggler.innerHTML='custom palette..';
        //basic = true;
    }
}
function raise_importance(id)
{
	el_imp = document.getElementById(id+'_w');
	if (el_imp.value == 1)
		el_imp.value = 3;
}
function fulltext_field_click()
{
    el_field = document.getElementById('fulltext_field');
    el_field.value = '';
}

function das_ticket_process()
{
	$.ajax({type: "POST", url: '/jwfind/das/das_ticket_process', data: 'resp='+window.location.hash, success: function(msg) {
		if (msg == 'ok')
		{
			loc = window.location.href.split('?');
			window.location = loc[0];
		}
		else
			window.location = 'http://'+document.domain+'/jwfind/jwpress/user/login';
	} });
}

function das_ticket_pickup() {
	setTimeout(function() {
		das_ticket_process();
		//alert(window.location.hash);
		//if (window.location.hash != '')
		//	window.location.hash = 'ok';
	}, 2000);
}
