var MaximumCharacters = "150";
var MaximumWords = "0";
var FormName = "masthead";
var TextFieldName = "comment";
var CharactersTypedFieldName = "CharsTyped";
var CharactersLeftFieldName = "CharsLeft";
var WordsTypedFieldName = "WordsTyped";
var WordsLeftFieldName = "WordsLeft";
var WordsMonitor = 0;
var MaxWords = parseInt(MaximumWords);
var MaxChars = parseInt(MaximumCharacters);
var textfield = 'document.' + FormName + '.' + TextFieldName + '.value';
var is_ajax = false;
var current_activity = 0;
$(document).ready(function(){

	$("#popupContactClose").click(function(){
		disablePopup();
	});

	$("#backgroundPopup").click(function(){
		disablePopup();
	});

	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});
     // 
       var user_id=$("#notification_user").val();
       if(user_id && user_id != "0" )
        {
            get_latest_updates();
            var holdTheInterval = setInterval(get_latest_updates, 10000);
        }
});
function populate_list(data,term) {
	var lis = document.getElementById('search_results');
	lis.innerHTML="";
	for(i=0;i<data.length;i++) {
	 lis.innerHTML +="<dt><a href=\"/show.php?result="+data[i][4]+"\">"+data[i][0]+"</a></dt><dd>"+data[i][1]+"<span class=\"display-url\"><a href=\"/show.php?result="+data[i][4]+"\">"+data[i][3].truncate(57)+"</a></span></dd>";
	}
	show_id('results');
//	new Effect.SlideDown('search_results');
}
function populate_related(data) {
	show_id('rel');
	var lis = document.getElementById('related_results');
	lis.innerHTML="";
	if (data) {
		for(i=0;i<data.length;i++) {
			message_text=format_message(data[i]);
					// 0 = term, 1 = network, 2 = label, 3 = act id, 4 = where, 5 = comment, 6= when, 7=date 8= who,9 = why,10 address, 11 site image, 12 share of not
			var find_string="By "+data[i][2];
			if (data[i][12]=="find") {
				var find_string="By <a href=\""+data[i][10]+"\" >"+data[i][2]+" on "+data[i][1]+"</a>";
			}
			if (data[i][12]=="contact") {
					if (data[i][11] != "phone.gif") {
						var find_string="<a href=\"mailto:"+data[i][10]+"\">"+data[i][2]+"  </a>";
					} else {
						var find_string=data[i][2]+" on "+data[i][10]+"";
					}
			}
			if (!data[i][11]) {
				data[i][11]="Google";
			} 
			if (!data[i][1]) {
				data[i][1]="shim";
			}
	// if we have contact me on show it, if we have find me on show it
			lis.innerHTML +="<dt><a href=\"javascript:recallSearch('"+data[i][0]+"','"+data[i][11]+"','"+data[i][10]+"','1');\">"+message_text+"</a> </dt><dd>"+find_string+"</dd>";
			
		}
	}
}
function popSelect (selbox,arrayname) {
	selbox.options.length = 0;
   for (var x = 0; x < arrayname.length; x++){
      var opt = new Option(arrayname[x][1], arrayname[x][0]);
       selbox[selbox.length] = opt;
      }
}

function show_hide(box,box2) {
	if (document.getElementById(box).style.display=='block') {
		document.getElementById(box).style.display='none';
		document.getElementById(box2).style.display='block';
	} else {
		document.getElementById(box).style.display='block';
		document.getElementById(box2).style.display='none';
	}	
}

function getPassword(pass) {
	if (pass.replace(/["']{1}/gi,"") != pass) {
	    var elem = document.getElementById('password_strength');
		elem.firstChild.nodeValue="Sorry quotes aren't allowed";
		return;
	}
		if (pass) {
			var p = new getpassword(getPasswordHandler);
			p.get_password(pass);
		} 
}
var getPasswordHandler = {
	// Function must have same name as remote method
	get_password: function(result) {
		eval(result);	
		if (password_value==4) {
			  var elem = document.getElementById('password_strength');

				elem.firstChild.nodeValue="Great";			
		} else if (password_value==3) {
					  var elem = document.getElementById('password_strength');

				elem.firstChild.nodeValue="Good";	
				
		} else if (password_value==2) {
					  var elem = document.getElementById('password_strength');

				elem.firstChild.nodeValue="OK";				
		} else if (password_value==1) {
					  var elem = document.getElementById('password_strength');

				elem.firstChild.nodeValue="Bad";					
		} else {
				var elem = document.getElementById('password_strength');
				elem.firstChild.nodeValue="";	
		}
	}
        
}

function checkUsername(username) {
	if (username.replace(/["']{1}/gi,"") != username) {
	    var elem = document.getElementById('username-signup-form');
		elem.firstChild.nodeValue="Sorry quotes aren't allowed in a username";
		return;
	}
		if (username) {
			var u = new checkusername(checkUsernameHandler);
			u.check_username(username);
		} 
}
var checkUsernameHandler = {
	check_username: function(result) {
		eval(result);		
		if (user=='exists') {
			  var elem = document.getElementById('username-signup-form');
				elem.firstChild.nodeValue="Sorry this Username already exists";
		} else {
				var elem = document.getElementById('username-signup-form');
				elem.firstChild.nodeValue="Available";	
		} 
	}
}


function get_latest_updates()
{
    var user_id=$("#notification_user").val();
   
    if(user_id && user_id != "0" )
        {
     
     
         var data = {
                    action: "get_user_updates",
                    user_id: user_id,
                    request_type:"ajax"
            };

            jQuery.post('/index.php', data, function(response)
            {                
                var user_updates = Array();
                try
                {
                    user_updates = $.secureEvalJSON(response);
                    show_user_updates(user_updates);
                }
                catch(ex)
                {
                    //show_results(user_updates);
                }

            });
               /* var u = new userupdates(userUpdatesHandler);
            u.get_user_updates(user_id);*/
        }
}
function show_user_updates(user_updates)
{
     var html = "";
     var total_updates = 0;
    if (user_updates && user_updates.length > 0) {
        total_updates = user_updates[0].total_updates;
        for(var i=0;i<user_updates.length;i++)
            {
                var class_css = "";
                if(user_updates[i].is_viewed == 0) {
                        class_css="not_viewed";
                    } else {
                       class_css="viewed";
                    }
                if(user_updates[i].update_type == "give_help")
                    {
                        html += "<li id='update_"+user_updates[i].id+"' class='"+class_css+"' > <a href='javascript:void(0)' onclick='delete_update("+user_updates[i].id+");' class='"+class_css+"' >delete</a>"+user_updates[i].nickname+" would like to help you on your <a href='"+user_updates[i].url+"' > post </a></li>"
                    }
                else if(user_updates[i].update_type == "get_help")
                    {
                        html += "<li id='update_"+user_updates[i].id+"' class='"+class_css+"'  > <a href='javascript:void(0)' onclick='delete_update("+user_updates[i].id+");' class='"+class_css+"'>delete</a>"+user_updates[i].nickname+" has asked for your help, on your <a href='"+user_updates[i].url+"' > post </a></li>"
                    }
               else if(user_updates[i].update_type == "join_conversation") {
                        html += "<li id='update_"+user_updates[i].id+"' class='"+class_css+"'  ><a href='javascript:void(0)' onclick='delete_update("+user_updates[i].id+");' class='"+class_css+"'>delete</a>"+user_updates[i].nickname+" has joined your <a href='"+user_updates[i].url+"' > conversation </a></li>"
                    }
               else if(user_updates[i].update_type == "thanked")
                    {
                        html += "<li id='update_"+user_updates[i].id+"' class='"+class_css+"'  ><a href='javascript:void(0)' onclick='delete_update("+user_updates[i].id+");' class='"+class_css+"'>delete</a> You have been thanked by "+user_updates[i].nickname+" on your <a href='"+user_updates[i].url+"' > post </a></li>"
                    }
                else if(user_updates[i].update_type == "cause")
                    {
                        html += "<li id='update_"+user_updates[i].id+"' class='"+class_css+"' ><a href='javascript:void(0)' onclick='delete_update("+user_updates[i].id+");' class='"+class_css+"'>delete</a>You can support a <a href='"+user_updates[i].url+"' > cause </a></li>"
                    }
                    total_updates++;
            }
        $("#nresults").html(html);
        if(total_updates == 0) {
                total_updates = "";
                $('#sp_count').removeClass("notices_active");
        		$('#sp_count').addClass("notices");
        } else {   
        	$('#sp_count').removeClass("notices");
        	$('#sp_count').addClass("notices_active");
		}
    } else {
            $("#nresults").html('<li>No notifications found</li>');
            $("#sp_count").html("");
    }

}
function mark_as_viewed(id)
{
    if(id != "0" && id != "")
        {
            $("#update_"+id).removeClass("not_viewed");
            var data = {
                    action: "mark_as_viewed",
                    update_id: id,
                    request_type:"ajax"
            };

            jQuery.post('/index.php', data, function(response)
            {
                 set_remaining_update_count(response);
            });
        }
}
function set_remaining_update_count(count)
{
   // var count = $("#sp_count").html();
    if(count == "0" || count == "")
        {
            $("#sp_count").html("");
        }
    else
        {
            $("#sp_count").html(count);
        }
}
function delete_update(id)
{
     if(id != "0" && id != "")
        {
            $("#update_"+id).remove();
           
            var data = {
                    action: "delete_update",
                    update_id: id,
                    request_type:"ajax"
            };

            jQuery.post('/index.php', data, function(response)
            {
               //  set_remaining_update_count(response);
            });
        }
}
function ValidateSignUp(thisform) {
var elem;
var errs=0;
var error_fields='\n';
var user=document.getElementById('username-signup').value;
var unquote_username=user.replace(/["']{1}/gi,"");
if (unquote_username != user) {
		errs += 1; 
		error_fields += String.fromCharCode(8226)+" Sorry Quotes are not allowed in your username<br />";
}

if (!validatePresent(document.getElementById('username-signup'), 'username-signup-form','true') ) {
		errs += 1; 
		error_fields += String.fromCharCode(8226)+" A trendy username<br />";
}
if (!validateEmail(document.getElementById('email-signup'), 'email-signup-form','true') ) {
		errs += 1; 
		error_fields += String.fromCharCode(8226)+" Your email address<br />";
}
if (!validatePresent(document.getElementById('password-signup'), 'password','true') ) {
		errs += 1; 
		error_fields += String.fromCharCode(8226)+" A top secret password<br />";
}
if (document.getElementById('tandc').checked != true) {
	errs+=1;
	error_fields +=String.fromCharCode(8226)+" Make sure you've ticked the box to say you've read the 'Terms & Conditions'\n";
}
if (errs>20)  {
	document.getElementById('sorry_message').innerHTML="Hold on there! You haven't quite entered all the essential info we need to know about you. Try again and check you've given us all the fields we need.<br />";
    $('#popupSorry').modal();
 	document.getElementById('message').innerHTML =error_fields;
} else if (errs>0)  {
	document.getElementById('sorry_message').innerHTML="Hold on there! You haven't quite entered all the essential info we need to know about you. Try again and check you've given us the following:<br />"+error_fields;
    $('#popupSorry').modal();
}
return (errs==0);
}
function validateUserName(vfld,ifld)
{

    var errs=0;  
    var user=document.getElementById(vfld).value;
    var unquote_username=user.replace(/["']{1}/gi,"");
    if (unquote_username != user) {
            errs += 1;
            msg (ifld, "error", "Sorry Quotes are not allowed in your username");
            setfocus(vfld);
    }
    if (!validatePresent(document.getElementById(vfld), ifld,'true') ) {
                    errs += 1;                   
    }
   return (errs==0);
}
function validateSettingsField(vfld,ifld) {
    var errs=0;
    if (!validatePresent(document.getElementById(vfld), ifld,'true') ) {
                    errs += 1;
    }
   return (errs==0);
}
function toggle_edit(type) {
	if (type == "contact") {
		if (document.getElementById('contact_data').style.display == "block") {
			document.getElementById('contact_data').style.display = "none";
			document.getElementById('contact_empty').style.display = "block";
		} else {
			document.getElementById('contact_empty').style.display = "none";
			document.getElementById('contact_data').style.display = "block";		
		}
	}
	if (type == "find") {
		if (document.getElementById('find_data').style.display == "block") {
			document.getElementById('find_data').style.display = "none";
			document.getElementById('find_empty').style.display = "block";
		} else {
			document.getElementById('find_empty').style.display = "none";
			document.getElementById('find_data').style.display = "block";		
		}
	}
}
function WordLengthCheck(s,l) {
WordsMonitor = 0;
var f = false;
var ts = new String();
for(var vi = 0; vi < s.length; vi++) {
	vs = s.substr(vi,1);
	if((vs >= 'A' && vs <= 'Z') || (vs >= 'a' && vs <= 'z') || (vs >= '0' && vs <= '9')) {
		if(f == false)	{
			f = true;
			WordsMonitor++;
			if((l > 0) && (WordsMonitor > l)) {
				s = s.substring(0,ts.length);
				vi = s.length;
				WordsMonitor--;
				}
			}
		}
	else {f = false;}
	ts += vs;
	}
return s;
} // function WordLengthCheck()

function CharLengthCheck(s,l) {
if(s.length > l) {s = s.substring(0,l);}
return s;
} // function CharLengthCheck()

function InputCharacterLengthCheck() {
if(MaxChars <= 0) {return;}
var currentstring = new String();
eval('currentstring = ' + textfield);
var currentlength = currentstring.length;
eval('currentstring = CharLengthCheck(' + textfield + ',' + MaxChars + ')');
if(CharactersLeftFieldName.length > 0) {
	var left = 0;
	eval('left = ' + MaxChars + ' - ' + textfield + '.length');
	if(left < 0) { 
	//	alert('change class');
		document.getElementById('CharsLeft').className='left_over';
//		left = 0; 
	} else {
		document.getElementById('CharsLeft').className='left';	
	}
	eval('document.' + FormName + '.' + CharactersLeftFieldName + '.value = ' + left);
//	if(currentstring.length < currentlength) { eval(textfield + ' = currentstring.substring(0)'); }
	}
if(CharactersTypedFieldName.length > 0) {
//	eval('document.' + FormName + '.' + CharactersTypedFieldName + '.value = ' + textfield + '.length');
//	if(currentstring.length < currentlength) { eval(textfield + ' = currentstring.substring(0)'); }
	}
} // function InputCharacterLengthCheck()

function InputWordLengthCheck() {
if(MaxWords <= 0) {return;}
var currentstring = new String();
eval('currentstring = ' + textfield);
var currentlength = currentstring.length;
eval('currentstring = WordLengthCheck(' + textfield + ',' + MaxWords + ')');
if (WordsLeftFieldName.length > 0) {
	var left = MaxWords - WordsMonitor;
	if(left < 0) {left = 0;}
	eval('document.' + FormName + '.' + WordsLeftFieldName + '.value = ' + left);
	if(currentstring.length < currentlength) {eval(textfield + ' = currentstring.substring(0)');}
	}
if (WordsTypedFieldName.length > 0) {
	eval('document.' + FormName + '.' + WordsTypedFieldName + '.value = ' + WordsMonitor);
	if(currentstring.length < currentlength) {eval(textfield + ' = currentstring.substring(0)');}
	}
} // function InputWordLengthCheck()

function InputLengthCheck() {
InputCharacterLengthCheck();
InputWordLengthCheck();

} // function InputLengthCheck()
function show_all_comments(commentid) {
	var ulid='commentList'+commentid;
	var morelabel='viewall'+commentid;
	var hidelabel='hideall'+commentid;
	uls=document.getElementById(ulid);
	var ulx, l, c, t;
	document.getElementById(morelabel).style.display='none';
	document.getElementById(hidelabel).style.display='block';
	for (var lis=0; lis<uls.childNodes.length; lis++){
		if (uls.childNodes[lis].className != "view_more") {
			uls.childNodes[lis].className='commentshow';	
		}
	}
	var helpbox='comment'+commentid;
	document.getElementById(helpbox).style.display='block';
}
function hide_all_comments(commentid) {
	var ulid='commentList'+commentid;
	var morelabel='viewall'+commentid;
	var hidelabel='hideall'+commentid;
	uls=document.getElementById(ulid);
	var ulx, l, c, t;
	document.getElementById(morelabel).style.display='block';
	document.getElementById(hidelabel).style.display='none';
	for (var lis=0; lis<uls.childNodes.length; lis++){
		if (uls.childNodes[lis].className != "view_more") {
			uls.childNodes[lis].className='commenthide';	
		}
	}
	var helpbox='comment'+commentid;
	document.getElementById(helpbox).style.display='none';
}

function check_clear(field,test) {
	 if (field.value == test) {
	 	field.value="";
	 }
}
function delquote(str){
	return (str=str.replace(/["']{1}/gi,""));
} 
var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread
function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};
function setFocusDelayed(vfld)
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}
function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
};
var proceed = 2;  

function commonCheck    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem) {
  	alert("debug error, missing field:"+ifld);
  }
  if (!elem.firstChild)
    return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node  
	if (!vfld) {
  	alert("debug error, missing field:"+vfld+"("+ifld+")");		
	}
  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "error", "  ERROR: required");  
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}
var proceed = 2;  

function commonCheckSelect    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem) {
  	alert("debug error, missing field:"+ifld);
  }
  if (!elem.firstChild)
    return true;  // not available on this browser

  if (elem.firstChild.nodeType != 3)
    return true;  // ifld is wrong type of node  
    if (!vfld[vfld.selectedIndex]) {
  	alert("debug error, missing field:"+vfld);    	
    }
    if (reqd && vfld[vfld.selectedIndex].value == 0) {
      msg (ifld, "error", "  ERROR: Please select a value");  
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;  
    }
 
  return proceed;
}
var proceed = 2;  

function commonCheckbox    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem) {
  	alert("debug error, missing field:"+ifld);
  }
  if (!elem.firstChild)
    return true;  // not available on this browser

  if (elem.firstChild.nodeType != 3)
    return true;  // ifld is wrong type of node  

    if (reqd && vfld.checked != true) {
      msg (ifld, "error", "  ERROR: If you agree with this statement please check the box");  
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;  
    }
 
  return proceed;
}
var proceed = 2;  

function commonCheckradio    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem) {
  	alert("debug error, missing field:"+ifld);
  }
  if (!elem.firstChild)
    return true;  // not available on this browser
  if (elem.firstChild.nodeType != 3)
    return true;  // ifld is wrong type of node  
    var countcheck;
    countcheck=0;
	  if (!vfld) {
  		alert("debug error, missing field:"+vfld);
  	}
		var j=vfld.length; 
		for (i=0; i<j; i++){

			if(vfld[i].checked) {

				countcheck++;
			}
		}
//		alert ("reqd"+reqd+"countcheck"+countcheck+"ifiedl"+ifld);
    if (reqd == true && countcheck==0) {
      msg (ifld, "error", "  ERROR: You must select an answer");  
      return false;
    } else {
      msg (ifld, "warn", " ");   // OK
      return true;  
    }
 
  return proceed;
}
function validateCheckbox(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheckbox (vfld, ifld, true);
  if (stat != proceed) return stat;

  msg (ifld, "warn", " ");  
  return true;
};
function validateRadio(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheckradio (vfld, ifld, true);
  if (stat != proceed) return stat;

  msg (ifld, "warn", " ");  
  return true;
};
function validateSelectBox(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheckSelect (vfld, ifld, true);
  if (stat != proceed) return stat;

  msg (ifld, "warn", " ");  
  return true;
};
function validatePresent(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) return stat;

  msg (ifld, "warn", " ");  
  return true;
};
function validateEmail  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "error", "Not a valid e-mail");
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg (ifld, "warn", "  Unusual e-mail");
  else
    msg (ifld, "warn", "");
  return true;
};
function validateTelnr  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "error", "  ERROR: not a valid telephone number. Characters permitted are digits, space ()- and leading +");
    setfocus(vfld);
    return false;
  }
  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (ifld, "error", "  ERROR: " + numdigits + " digits - too short");
    setfocus(vfld);
    return false;
  }

  if (numdigits>14)
    msg (ifld, "warn", numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (ifld, "warn", "  Only " + numdigits + " digits - check if correct");
    else
      msg (ifld, "warn", "");
  }
  return true;
};
function validateAge    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg (ifld, "error", "  ERROR: not a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>=200) {
    msg (ifld, "error", "  ERROR: not a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>110) msg (ifld, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg (ifld, "warn", "Bit young for this, aren't you?");
    else        msg (ifld, "warn", "");
  }
  return true;
};
function validatePassword    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd,vfldp)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;
 	var invalid=" ";
  // if it contains spaces or quotes do not allow it
  if ((vfld.value.indexOf(invalid) > -1) || (vfldp.value.indexOf(invalid) > -1)) {
    msg (ifld, "error", "  ERROR: not a valid password please do not use spaces in your password");
    setfocus(vfld);
    return false;
  }
  if (vfld.value != vfldp.value && vfld.value != "" && vfldp.value != "") {
    msg (ifld, "error", "  ERROR: your passwords do not match please recheck");
    setfocus(vfld);
    return false;
  } else {
    msg (ifld, "warn", "");  	
  }
  return true;
};

function doCaptcha(challenge_field,response_field) {
		if (challenge_field && response_field) {
			var d = new docaptcha(doCaptchaHandler);
			d.do_captcha(challenge_field,response_field);
		} else {
			return false;
		}
}
var doCaptchaHandler = {
	do_captcha: function(result) {
		eval(result);
		if (captcha=="ok") {
		 	document.getElementById('home_form').submit();
		}
	}
}

function populate_latest() {

	getTwitter('looking for help');
}
function getTwitter(search_term) {
		start=0;
		guid=9;
		user_id=5;
		code="json";
		client='';
		count=8;
		start_id=0;
		if (search_term) {
			var e = new gettwitter(getTwitterHandler);
			e.get_twitter(search_term,start,guid,user_id,code,client,count,start_id);
		} else {
			return false;
		}
}
function getLatestTwitter(search_term) {
		var start_id=document.getElementById('max_twitter_id').value;
		var start=0;
		var guid=9;
		var user_id=5;
		var code="json";
		var client='';
		var count=1;
		if (search_term) {
			var e = new gettwitter(getLatestTwitterHandler);
			e.get_twitter(search_term,start,guid,user_id,code,client,count,start_id);
		} else {
			return false;
		}
}
var counter=0;
var getTwitterHandler = {
	get_twitter: function(result) {	
		eval(result);

		if (search_results.length > 0) {
			document.getElementById('max_twitter_id').value=max_id;
			populate_latest2(search_results);
		}
	}
}
var getLatestTwitterHandler = {
	get_twitter: function(result) {	
		eval(result);
		if (search_results.length > 0) {
			document.getElementById('max_twitter_id').value=max_id;
			populate_latest2(search_results);
		}
	}
}
function add_latest(hdata) {
		for(i=0;i<hdata.length;i++) {		
				var box='<li class="last_what" id="item_latest_tab2'+ i + '">';
				box +='<a class="lightblue" style="clear:left;" href="/related-searches/<%replace_hyphens input=$related_results[l1].term%>/<%$related_results[l1].activity_id%>.htm" title="someone is looking for <%$related_results[l1].term%>">';
				box +='<img width="45" height="45" src="'+hdata[i][5]+'" alt="'+hdata[i][3]+'" />';
				box +='<a  style="clear:left" class="lightblue" href="/related-searches/<%replace_hyphens input=$latest[l1].term%>/<%$latest[l1].activity_id%>.htm" title="'+hdata[i][3]+'" /><em>'+htmlspecialchars_decode(hdata[i][1])+'</em></a></li>';
				addItem('latest_tab2',box);		
		}
		
}

function populate_latest2(hdata) {
		for(i=0;i<hdata.length;i++) {
				var box='<li class="last_what"  style="display:none;" id="item_latest_tab2'+ counter + '">';
				box +='<a class="lightblue" style="clear:left;" href="/related-searches/<%replace_hyphens input=$related_results[l1].term%>/<%$related_results[l1].activity_id%>.htm" title="someone is looking for <%$related_results[l1].term%>">';
				box +='<img width="45" height="45" src="'+hdata[i][5]+'" alt="'+hdata[i][3]+'" />';
				box +='<a  style="clear:left" class="lightblue" href="/related-searches/<%replace_hyphens input=$latest[l1].term%>/<%$latest[l1].activity_id%>.htm" title="'+hdata[i][3]+'" /><em>'+htmlspecialchars_decode(hdata[i][1])+'</em></a></li>';
				addItem('latest_tab2',box);		
		}
}


function htmlspecialchars_decode (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Mateusz "loonquawl" Zalega
    // +      input by: ReverseSyntax
    // +      input by: Slawomir Kaniecki
    // +      input by: Scott Cariss
    // +      input by: Francois
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
    // *     returns 1: '<p>this -> &quot;</p>'
    // *     example 2: htmlspecialchars_decode("&amp;quot;");
    // *     returns 2: '&quot;'

    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined') {
        quote_style = 2;
    }
    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
        // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
    }
    if (!noquotes) {
        string = string.replace(/&quot;/g, '"');
    }
    // Put this in last place to avoid escape being double-decoded
    string = string.replace(/&amp;/g, '&');
    return string;
}

function addItem(id,item) {
			if (counter>=7) {
				removeItem(id);
			}
			$('#'+id).prepend(item);
 		    $('#item_'+id + counter).slideDown('1200');
  		    counter += 1;						
}		
function removeItem(id) {
	$('#item_'+id + (counter-7)).slideUp();
}	
function open_search() {
	document.getElementById('search_again').style.display='none';
	document.getElementById('what_again').style.display='block';     	 
	$('#search_again_panel').slideDown('slow', function() {
		document.getElementById('results_container').className="search_again";
	});
}
function close_search() {

    document.getElementById('what_again').style.display='none'; 
     $('#search_again_panel').slideUp('slow', function() {
		document.getElementById('results_container').className="";
	document.getElementById('search_again').style.display='block';
});    		
}
function open_give() {
	document.getElementById('give_again').style.display='none';
	document.getElementById('how_again').style.display='block'; 	 
	$('#give_again_panel').slideDown('slow', function() {
		document.getElementById('results_container').className="give_again";
	});
}
function close_give() {
    document.getElementById('how_again').style.display='none'; 
     $('#give_again_panel').slideUp('slow', function() {
		document.getElementById('results_container').className="";
		document.getElementById('give_again').style.display='block';
	});    		
}

/***************************************************************************************
                    twitter.js
****************************************************************************************/

function checkforSubmit(e)
{
    
    if(e.keyCode==13 ){
        validateTwitter();
		}
}
function showLoginPopup()
{
    window.open ("/twitter_login.php","mywindow","menubar=0,resizable=0,width=380,height=250,top=250px,left=400px");
}
function validateTwitterForm()
{
   if (!validateEmail(document.getElementById('txt_email'), 'twitter-email','true') )
    {
	 	return false
    }
    return true;
}
function validateTwitter()
{

    email = $("input#txt_email").val();
    pass = $("input#twitter_password").val();

    var html = $.ajax({
    type: "POST",
    url: "/twitter/twitter_user.php",
    data: "username=" + email + "&password=" + pass,
    async: false
    }).responseText;
    if(html=="success"){
        //location.reload();
        window.location.href='/index.php';
    }
    else
        $("#error").html(html);
}

/***************************************************************************************
                    recaptch.js
****************************************************************************************/
var form_id = "";
var field_id = "";
function containsURL(formId,fid)
{
    form_id = formId;
    field_id = fid;
    var contains = false;
    var search_term = $("#"+fid).val();
    var search_url = search_term.split(" ");
    if (fid=="search_term") {
    if (search_term==$('#default_get_help').val() || search_term=="") {
    	$('#popupSorry').modal();
    	return false;
    }
    } else {
 	if (search_term==$('#default_give_help').val() || search_term=="") {
 		document.getElementById('sorry_message').innerHTML='Woops! You left the form blank, you need to say what you can help with';
    	$('#popupSorry').modal();
    	return false;
    }    
    }
    for(var i=0;i<search_url.length;i++)
        {
            if(isValidURL(search_url[i]))
                {
                    showCaptcha();
                    contains = true;
                    break;
                }
        }        
   if(!contains)
       {
          $("#"+formId).submit();
       }
    return false;

}
function showCaptcha()
{

    centerPopup();
    loadPopup();
    javascript:scroll(0,0);
    return false;

}

function isValidURL(url)
{
    var urlRegxp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    if (urlRegxp.test(url) != true)
        {
            return false;
        }
    else
        {
           return true;
        }
}
function validateCaptcha()
{

    challengeField = $("input#recaptcha_challenge_field").val();
    responseField = $("input#recaptcha_response_field").val();
    var html = $.ajax({
    type: "POST",
    url: "/includes/recaptcha.php",
    data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
    async: false
    }).responseText;
    if(html == "success")
    {
        disablePopup();
        if(is_ajax)
            {
                $("#is_recaptched_message_"+current_activity).val("true");
                add_comment_ajax(current_activity);
                return false;
            }
        $("#is_recaptched_message_"+current_activity).val("true");
        $("#commentfrm_"+current_activity).submit();
        return true;
    }
    else
    {
        $("#captchaStatus").html("Your captcha is incorrect. Please try again");
        Recaptcha.reload();
        return false;
    }
return false;
}
/***************************************************************************************
                    popup.js
****************************************************************************************/


var popupStatus = 0;


function loadPopup(){

	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.8"
		});
                $("#video").css({
			"display": "none"
		});

		$("#backgroundPopup").fadeIn("slow");
		$("#popupContact").fadeIn("slow");
		popupStatus = 1;
	}
}

function disablePopup(){

	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("slow");
		$("#popupContact").fadeOut("slow");
                $("#video").css({
			"display": "block"
		});
		popupStatus = 0;
	}
}


function centerPopup(){

	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupContact").height();
	var popupWidth = $("#popupContact").width();

        $("#popupContact").css({
		"position": "absolute",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2
	});


	$("#backgroundPopup").css({
		"height": windowHeight
	});

}

function get_twitter_posts_html(keyword,action)
{
    $("#empty").css("display","none");
     var data = {
		action: 'twitter_posts',
		search_term: keyword
	};
	jQuery.post('/index.php', data, function(response)
        {
          
          var posts = Array();
                try
                {
                    posts = $.secureEvalJSON(response);
                    show_results(posts,action);
                }
                catch(ex)
                {
                    show_results(posts,action);
                }

        });
}
function show_results(posts,action)
{
    
    if(posts.length > 0)
        {
            var html = '';
            html += '<dd>';
                html += '<hr/>';
                html += '</dd>';
                var loggedin_user = Array();
            if(posts[0].logged_in && posts[0].logged_in != "undefined")
                {
                   loggedin_user = posts[0].logged_in;
                }
            for(var i=0;i<posts.length;i++)
            {
               var message_html = get_messages_html(posts[i].messages,posts[i].id,loggedin_user,action);

                var image_url = posts[i].user_image;
                if(image_url.indexOf("http") < 0)
                    {
                        image_url = posts[i].site + posts[i].user_image;
                    }
                html += '<dt class="'+posts[i].help_type+'" id="post_'+posts[i].id+'">';
                html += '<div class="results_left">';
                html += '<a href="'+posts[i].user_profile+'"  target="_blank"><img src="'+image_url+'"alt="'+posts[i].nickname+'"></a>';
                html += '<div class="points"><p>'+posts[i].points+'</p></div>';
                html += '</div>';
                html += '<div class="results_main">';
                html += '<div style="float: left;">';
                html +='<p>'+posts[i].nickname+' '+posts[i].term_type+'  <strong>'+posts[i].term+'</strong></p>';
                html += '<p class="time">';
                html += '<em>'+posts[i].timestamp+'</em>';
                html += '</p>';
                html += '</div>';
                html += '</div>';
                html += '<div class="results_right">';                
                if(posts[i].message_count > 0)
                    {
                        html += '<p class="answers"><span id="answer_count'+posts[i].id+'">'+posts[i].message_count+'</span> answer</p>';
                    }
                html += '<p class="helpthemout">';
               
                if(posts[i].message_count > 0)
                    {
                       // html += ' | ';
                        html += '  <a href="javascript:void(0);" onclick="show_comments('+posts[i].id+');" id="show_'+posts[i].id+'"> view answers </a>';
                        html += '  <a href="javascript:void(0);" onclick="hide_comments('+posts[i].id+');" id="hide_'+posts[i].id+'" style="display:none;"> hide answers </a>';
                    }
                 else
                     {
                          html += '<a href="javascript:void(0);" onclick="show_comments('+posts[i].id+');"> help them out </a> ';
                     }
                html += '</p>';
                html +='<p class="flag"><a href="javascript:void(0);" onclick="set_abuse_params('+posts[i].id+',\'\',\'add_abuse\');$(\'#abuse\').modal();" >flag as inappropriate</a></p>';
                html += '</div>';
                html += '<div class="clear"></div>';
                html += '</dt>';                
                html += '<dd id="post_comments_'+posts[i].id+'">'+message_html+'</dd>';
                html += '<dd>';
                html += '<hr  id="line_comments_'+posts[i].id+'" />';
                html += '</dd>';
                html += '<div class="clear"></div>';
            }
            html += '';
            $("#twitter_results").html(html);
        }
     else
         {
            var error_msg = "Sorry no results were found on twitter";
            // $("#twitter_results").html(""+error_msg+"");
            $("#empty").css("display","block");
         }
         //show_results_div();
}
function show_comments(activity_id) {
    $("#commentList"+activity_id).css("display","block");
    $("#hide_"+activity_id).css("display","block");
    $("#show_"+activity_id).css("display","none");
    $("#frm_"+activity_id).css("display","block");
}
function hide_comments(activity_id) {
    $("#commentList"+activity_id).css("display","none");
    $("#hide_"+activity_id).css("display","none");
    $("#show_"+activity_id).css("display","block");
    $("#frm_"+activity_id).css("display","none");
}
function get_messages_html(messages,activity_id,loggedin_user,help_type)
{
  var messages_html = '<ul id="commentList'+activity_id+'" style="display:none;">';
  var flag_html = "";
  
  for(var i=0;i<messages.length;i++)
      {
         var image_url = messages[i].user_image;
            if(image_url.indexOf("http") < 0)
                {
                    image_url = messages[i].site + messages[i].user_image;
                }
        var remove_link = "";
       var thank_html = '<div id="thank_button_'+messages[i].message_id+'">';
        var thanks_btn = '';
        if(loggedin_user[0] && loggedin_user[0].id == messages[i].user_id)
            {
                 remove_link = "<a title='Remove post' onclick='remove_comment("+activity_id+","+help_type+","+messages[i].message_id+","+help_type+"); href='javascript:void(0);' class='darkblue'>remove</a>";

            }
        if((loggedin_user[0] && loggedin_user[0].id != messages[i].user_id))
            {
                flag_html = '<a href="javascript:void(0);" onclick="set_abuse_params('+activity_id+','+messages[i].message_id+',\'add_comment_abuse\');$(\'#abuse\').modal();" >flag</a>';
                if (messages[i].thanked == "false")
                {
                    var thanks_link = 'thank_ajax(\''+help_type+'\','+activity_id+','+messages[i].message_id+','+messages[i].user_id+','+loggedin_user[0].id+',\''+help_type+'\')';
                    thanks_btn = '<input type="button" name="thank" value="Thanks" class="thank" onclick="'+thanks_link+'"/>';
                }
                else
                {
                    thanks_btn = '<input type="button" name="thanked" value="Thanked" class="thanked"  />';
                }
            }
        thank_html += thanks_btn+'</div>';
        
        messages_html += '<li id="conversation_'+messages[i].message_id+'" class="commentshow">';
        messages_html += '<div class="answers_left"><a href="'+messages[i].user_profile+'"><img width="75" src="'+image_url+'" alt="Profile Image"/></a>';
        messages_html += '<div class="points"><p>'+messages[i].points+'</p></div></div>';
        messages_html += '<div class="answers_main">';
        messages_html += '<div style="float: left;">';
        messages_html += '<p><strong>'+messages[i].message+'</strong> by <a class="darkblue" href="'+messages[i].user_profile+'">'+messages[i].nickname+'</a></p>';
        messages_html += '<p class="time"><em>  weeks ago</em></p></div></div>';
        messages_html += '<div class="answers_right">'+thank_html+'<p class="flag">'+remove_link+' '+flag_html+'</p></div><div class="clear"></div>';
        messages_html += '</li>';
      }
      messages_html += '</ul>';
      messages_html += '<ul>';
      messages_html +='<li class="help" style="display:none;" id="frm_'+activity_id+'">';
      messages_html += get_comment_form(loggedin_user,activity_id,help_type);
      messages_html +='</li>';
      messages_html += '</ul>';
      
      return messages_html;
}
function get_comment_form(loggedin_user,activity_id,help_type)
{
    var frmHtml = "";
    if(loggedin_user[0])
        {
            var help_text = "";
            if (help_type == "get_help" || help_type ==  "recall_get_help" || help_type ==  "related_get_help")
                {
                   help_text ="ask for help here"
                }
            else if(help_type ==  "give_help" || help_type ==  "recall_give_help" || help_type ==  "related_give_help")
              {
                   help_text ="help out here...";

              }
            frmHtml='<form method="post" action="/index.php#post_top'+activity_id+'" id="commentfrm_'+activity_id+'" onsubmit="return add_comment(\''+activity_id+'\',\'message_'+activity_id+'\');">'
                    +'<div class="answers_left">'
                            +'<a href="/profile.php?profile_id='+loggedin_user[0].id+'"><img width="75" src="'+loggedin_user[0].image+'" id="user_img_'+activity_id+'" alt="Profile Image"/></a>'
                            +'<div class="points">'+loggedin_user[0].points+'</p></div>'
                    +'</div>'
                    +'<div class="answer" >'
                    +'<input type="hidden" name="action" id="action_'+activity_id+'" value="related_get_help" />'
                    +'<input type="hidden" name="method" value="add_ping" />'
                    +'<input type="hidden" name="activity_id" id="search_id_'+activity_id+'"  value="'+activity_id+'" />'
                    +'<input type="hidden" name="help_type" id="help_type'+activity_id+'" value="'+help_type+'" />'
                    +'<input type="hidden" name="activity_id" value="'+activity_id+'" />'
                    +'<input type="hidden" name="result_id" id="result_id_'+activity_id+'" value="'+activity_id+'" />'
                    +'<textarea class="message" name="message" id="message_'+activity_id+'" rows="5" cols="40" onclick="check_clear(this,\''+help_text+'\');"></textarea>'
                    +'<p><input type="submit" id="btnAdd'+activity_id+'" name="give_help" value="Give Help" class="submit" onmouseover="this.className=\'submit_over\';" onmouseout="this.className=\'submit\';"/></p>'
                    +'</form>'
                    +'<div class="clear"></div>'
                    +'</div>';
        }
    else
        {
            
            if (help_type == "get_help" || help_type ==  "recall_get_help" || help_type ==  "related_get_help")
                {
                   help_text ="people ask you for help."
                }
            else if(help_type ==  "give_help" || help_type ==  "recall_give_help" || help_type ==  "related_give_help")
              {
                   help_text ="people offer to help.";

              }
            frmHtml = '<form method="post" action="/index.php">'
                    +'<div class="postsign">'
                    +'<input type="button" name="join" value="Join" class="post_join" onmouseover="this.className=\'post_join_over\';" onmouseout="this.className=\'post_join\';" onclick="document.location=\'/register.php\';"/>'
                    +'<input type="button" name="login" value="Log In" class="post_login" onmouseover="this.className=\'post_login_over\';" onmouseout="this.className=\'post_login\';" onclick="$(\'#signin_panel\').modal();"/>'
                    +'<p>Join or log in to post your request and be alerted when  '+help_text+'</p>'
                    +'</div>'
                    +'</form>';

        }
     return frmHtml;
}
function show_required_div(id) {

              $(".sett").each(function (i) {

                   if(this.id == id)
                        {
                            this.style.display="block";
                        }
                    else
                        {
                            this.style.display="none";
                        }

                });
            }

/* REMOVE BUTTON */
function showRemoveButton(id)
{
   var remove_id = id.split("_");   
   $("#remove_"+remove_id[1]).css("display","block");
   
}
function hideRemoveButton(id)
{
    var remove_id = id.split("_");
   $("#remove_"+remove_id[1]).css("display","none");
}
function showRemoveCommentButton(id)
{
   var remove_id = id.split("_");
   $("#remove_comment_"+remove_id[1]).css("display","block");

}
function hideRemoveCommentButton(id)
{
    var remove_id = id.split("_");
   $("#remove_comment_"+remove_id[1]).css("display","none");
}
/*  ASK A FRIEND */
function showAskFriend(activity_id,search_term,action)
{
	document.getElementById('ask_term').innerHTML=search_term;
	document.getElementById('ask_search_term').value=search_term;
	document.getElementById('ask_activity_id').value=activity_id;
    $("#friend_panel").modal();
}
/* Show current post comments */
function show_post_comments(activity_id)
{
    $('#commentList'+activity_id).css('display','block');
    $('#post_hideall').css('display','block');
    $('#post_viewall').css('display','none');
    $('#postComment_form').css('display','block');

}
function hide_post_comments(activity_id)
{
    $('#commentList'+activity_id).css('display','none');
    $('#post_hideall').css('display','none');
    $('#post_viewall').css('display','block');
    $('#postComment_form').css('display','none');

}
function notificationShow() {
var val = document.getElementById("ndiv").style.display;
	if(val == "none") {
		document.getElementById("ndiv").style.display ="";
	} else {
		document.getElementById("ndiv").style.display ="none";
	}
}
function set_abuse_params(ab_activity_id,ab_message_id,abuse_type) {
	document.getElementById('abuse_activity_id').value=ab_activity_id;
	document.getElementById('abuse_message_id').value=ab_message_id;
	document.getElementById('abuse_method').value=abuse_type;
}
function check_for_reason(field_id)
{ 
    var reason = $("#"+field_id).val();       
    reason = reason.replace(new RegExp(/^\s+/),"");
    reason = reason.replace(new RegExp(/\s+$/),"");    
     if(reason == "Give reason here..." || reason == "")
         {                
                $("#ab_error").text("Please give some reason");
                return false;
         }
         flag_post(field_id);
   return false;
}
function flag_post(field_id)
{
    var action = $("#abuse_action").val();
    var help_type=$("#abuse_help_type").val();
    var method = $("#abuse_method").val();
    var activity_id = $("#abuse_activity_id").val();
    var message_id = $("#abuse_message_id").val();
    var reason = $("#"+field_id);
    var result_id=$("#abuse_result_id");
    var answer_count = $("#answer_count"+activity_id).text();
    var data = {
		action: action,
		abuse_help_type: help_type,
                result_id: result_id,
                activity_id:activity_id,
                message_id:message_id,
                reason:reason,
                method:method,
                answer_count:answer_count,
                request_type:"ajax"
	};
    jQuery.post('/index.php', data, function(response)
        {
            if(method=="add_abuse")
                {
                    $("#post_comments_"+activity_id).remove();
                    $("#post_"+activity_id).remove();
                    $("#line_comments_"+activity_id).remove();
                }
             else
                 {
                    $("#conversation_"+message_id).remove();
                    answer_count = answer_count-1;
                    $("#answer_count"+activity_id).text(answer_count);


                 }
                 $.modal.close();
        });
}
function Trim(input)
  {
    var lre = /^\s*/;
    var rre = /\s*$/;
    input = input.replace(lre, "");
    input = input.replace(rre, "");
    return input;
   }
   function UploadFile()
        {
         //debugger;
         var user_img = document.getElementById("upload_image");          
          var FileName = user_img.value;
          var isValid = false;
          var error_msg = '';
          
          if(Trim(FileName) == '')
            {
              error_msg = 'Please select a file to upload';
              $("#img_error").html(error_msg);
              user_img.focus();
              return false;
            }
          var extArray = new Array(".jpg",".png");
          // getting FileName
           File = FileName;
             while (File.indexOf("\\") != -1)
                File = File.slice(File.indexOf("\\") + 1);
          
          // alert("File name = " + File);
           //getting Extension

           var ext = File.slice(File.indexOf(".")).toLowerCase();

           for (var i = 0; i < extArray.length; i++)
               {
                 if (extArray[i] == ext)
                 {
                   isValid = true;
                 }
               }

              if(isValid == false)
                {
                    error_msg = "Please only upload files that end in types:  "
                            + (extArray.join("  ")) ;
                    $("#img_error").html(error_msg);
                         user_img.focus();
                      return false;
                }
              else
                {
                 return true;

                }
        }
   
   function add_comment(activity_id,fid)
   {
      current_activity = activity_id;
      is_ajax = true;

    var search_term = $("#message_"+activity_id).val();
    if(search_term != "")
        {
            var search_url = search_term.split(" ");
            var contains = false;
              for(var i=0;i<search_url.length;i++)
                {
                    if(isValidURL(search_url[i]))
                        {
                            showCaptcha();
                            contains = true;
                            break;
                        }
                }
                if(!contains)
                    {
                        add_comment_ajax(activity_id);
                    }
        }
      else
          {
                //$('#popupSorry').modal();
          }
     return false;
   }
   function add_comment_ajax(activity_id)
   {
      var help_type=$("#help_type"+activity_id).val();
      var result_id = $("#result_id_"+activity_id).val();
      var act_id = $("#search_id_"+activity_id).val();
      var submit_action = $("#action_"+activity_id).val();
      var comment = $("#message_"+activity_id).val() ;
      var answer_count = $("#answer_count"+activity_id).text();
      var image_url = $("#user_img_"+activity_id).attr('src');
      var recaptched =  $("#is_recaptched_message_"+current_activity).val();
      $("#btnAdd"+activity_id).attr('disabled',true);
      $("#message_"+activity_id).attr('disabled',true);
      is_ajax = true;

       var data = {
		action: submit_action,
		help_type: help_type,
                result_id: result_id,
                activity_id:act_id,
                message:comment,
                method:"add_ping",
                answer_count:answer_count,
                is_recaptched:recaptched,
                request_type:"ajax"
	};

	jQuery.post('/index.php', data, function(response)
        {

          var message = Array();
                try
                {
                    message = $.secureEvalJSON(response);
                  //  alert('message'+message);
                    show_new_comment(message[0],image_url,activity_id);
                    //  alert(help_type+" "+result_id+" "+act_id+" "+submit_action+" "+comment+" "+answer_count);
                }
                catch(ex)
                {
                     enable_fields(activity_id);
                }

        });
              
        return false;
   }
function stripslashes(str) {
str=str.replace(/\\'/g,"'");
str=str.replace(/\\/g,"");
str=str.replace(/\'/g,"'");
str=str.replace(/\\"/g,'"');
str=str.replace(/\\0/g,'\0');
str=str.replace(/\\\\/g,'\\');
return str;
}
   function show_new_comment(message,image_url,activity_id)
   {
        if(message.moderation)
            {
                $('#moderation_panel').modal();
                enable_fields(activity_id);
                return false;
            }
        var messages_html = "";
        var points = 0;
        if(message.points != "")
            {
                points = message.points;
            }
        //var remove_link = "<a title='Remove post' href='/index.php?action="+message.action+"&activity_id="+activity_id+"&method=remove_conversation&message_id="+message.message_id+"&help_type="+message.help_type+"' class='darkblue'>remove</a>";
        var remove_click= 'remove_comment("'+activity_id+'","'+message.action+'","'+message.message_id+'","'+message.help_type+'");';
        var remove_link = "<a title='Remove post' href='javascript:void(0);' class='darkblue' onclick='"+remove_click+"'>remove</a>";
        messages_html += '<li id="conversation_'+message.message_id+'" class="commentshow">';
        messages_html += '<div class="answers_left"><a href="'+message.user_profile+'"><img width="75" src="'+image_url+'" alt="Profile Image"/></a>';
        messages_html += '<div class="points"><p>'+points+'</p></div></div>';
        messages_html += '<div class="answers_main">';
        messages_html += '<div style="float: left;">';
        messages_html += '<p><strong>'+stripslashes(message.comment)+'</strong> by <a class="darkblue" href="'+message.user_profile+'">'+message.nickname+'</a></p>';
        messages_html += '<p class="time"><em>just now</em></p></div></div>';
        messages_html += '<div class="answers_right"><p class="flag">'+remove_link+'</p></div><div class="clear"></div>';
        messages_html += '</li>';
        $("#commentList"+activity_id).append(messages_html);
        $("#answer_count"+activity_id).text(message.answer_count);
        $("#message_"+activity_id).val(" ");
        enable_fields(activity_id);
        
   }
   function enable_fields(activity_id)
   {
        $("#message_"+activity_id).removeAttr('disabled');
        $("#btnAdd"+activity_id).removeAttr('disabled');
   }
   function remove_comment(activity_id,action,message_id,help_type,user_id)
   {
        var answer_count = $("#answer_count"+activity_id).text();
        var data = {
		action: action,
		help_type: help_type,
                activity_id:activity_id,
                message_id:message_id,
                method:"remove_conversation",
                request_type:"ajax"
	};

	jQuery.post('/index.php', data, function(response)
        {          $("#conversation_"+message_id).remove();
                    answer_count = answer_count-1;
                    $("#answer_count"+activity_id).text(answer_count);

                //alert("");

        });
        return false;
   }
   function show_remaining_messages(messages,activity_id,action,help_type,user_id)
   {
      // alert(messages[0].icon_path);
      
        var messages_html = "";
        for(var i=0;i<=messages.length;i++)
            {
                var thanks_btn = '<input type="button" name="thanked" value="Thanked" class="thanked"  />';
                if(messages[i].thanked == false)
                    {
                        var thanks_link = "/index.php?action=recall_get_help&amp;activity_id="+activity_id+"&amp;method=thank&amp;message_id="+messages[i].message_id+"&amp;thanked_to="+messages[i].user_id+"&amp;thanked_by="+user_id+"&amp;help_type="+help_type;
                        thanks_btn = '<input type="button" name="thank" value="Thanks" class="thank" onclick="document.location="'+thanks_link+'"/>';
                    }
                var remove_link = "<a title='Remove post' onclick='remove_comment("+activity_id+","+action+","+messages[0].message_id+","+help_type+"); href='javascript:void(0);' class='darkblue'>remove</a>";
                var profile_link="/profile.php?profile_id="+user_id;
                var image_url = "";
                if(messages[i].thumbnail_icon != "")
                if(image_url.indexOf("http") < 0)
                    {
                        image_url = messages[i].site + posts[i].user_image;
                    }
                messages_html += '<li id="conversation_'+messages[i].message_id+'" class="commentshow">';
                messages_html += '<div class="answers_left"><a href="'+profile_link+'"><img width="75" src="'+image_url+'" alt="Profile Image"/></a>';
                messages_html += '<div class="points"><p>'+messages[i].points+'</p></div></div>';
                messages_html += '<div class="answers_main">';
                messages_html += '<div style="float: left;">';
                messages_html += '<p><strong>'+messages[i].comment+'</strong> by <a class="darkblue" href="'+messages[i].user_profile+'">'+messages[i].nickname+'</a></p>';
                messages_html += '<p class="time"><em>just now</em></p></div></div>';
                messages_html += '<div class="answers_right">'+thanks_btn+'<p class="flag">'+remove_link+'</p></div><div class="clear"></div>';
                messages_html += '</li>';
                $("#commentList"+activity_id).append(messages_html);
                $("#answer_count"+activity_id).text(message.answer_count);
                $("#message_"+activity_id).val(" ");
            }
        

   }
   function thank_ajax(action,activity_id,message_id,thanked_to,thanked_by,help_type)
   {
     var method = "thank";
     $("#thank_button_"+message_id).html('<input type="button" name="thanked" value="Thanked" class="thanked" />');
     var data = {
		action: action,
		help_type: help_type,
                activity_id:activity_id,
                message_id:message_id,
                method:method,
                thanked_to:thanked_to,
                thanked_by:thanked_by,
                request_type:"ajax"
	};       
                
	jQuery.post('/index.php', data, function(response)
        {
            
        });
   }

function validateEmailAddress()
{
    var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
      if (!email.test($('#txt_email_address').val())) {
           $("#error_email").html("Invalid email address");
            return false
      }
   
    return true;
}
