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';

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 u = new userupdates(userUpdatesHandler)
            u.get_user_updates(user_id);
        }
}
var userUpdatesHandler = {
	// Function must have same name as remote method
	get_user_updates: function(result) {
		eval(result);
               var html = "";
               
               
		if (user_updates && user_updates.length > 0) {
                    for(var i=0;i<user_updates.length;i++)
                        {
                            var class_css = "";
                            if(user_updates[i][5] == 0)
                                {
                                    class_css="not_viewed";
                                }
                            if(user_updates[i][2] == "give_help")
                                {
                                    html += "<p class='"+class_css+"' onmouseover='mark_as_viewed("+user_updates[i][4]+");' onmouseout='hide_delete();'> <span style='float:right'><a href='javascript:void(0)' onclick='delete_update("+user_updates[i][4]+");'>delete</a></span> <br class='clear'/>"+user_updates[i][1]+" would like to help you on your <a href='"+user_updates[i][0]+"' > post </a></p>"
                                }
                            else if(user_updates[i][2] == "get_help")
                                {
                                    html += "<p class='"+class_css+"'  onmouseover='mark_as_viewed("+user_updates[i][4]+");'> <span style='float:right'><a href='javascript:void(0)' onclick='delete_update("+user_updates[i][4]+");'>delete</a></span> <br class='clear'/>"+user_updates[i][1]+" has asked for your help, on your <a href='"+user_updates[i][0]+"' > post </a></p>"
                                }
                           else if(user_updates[i][2] == "join_conversation")
                                {
                                    html += "<p class='"+class_css+"'  onmouseover='mark_as_viewed("+user_updates[i][4]+");'><span style='float:right;display:block'><a href='javascript:void(0)' onclick='delete_update("+user_updates[i][4]+");'>delete</a></span><br class='clear'/>"+user_updates[i][1]+" has joined your <a href='"+user_updates[i][0]+"' > conversation </a></p>"
                                }
                           else if(user_updates[i][2] == "thanked")
                                {
                                    html += "<p class='"+class_css+"'  onmouseover='mark_as_viewed("+user_updates[i][4]+");'> <span style='float:right'><a href='javascript:void(0)' onclick='delete_update("+user_updates[i][4]+");'>delete</a></span> <br class='clear'/> You have been thanked by "+user_updates[i][1]+" on your <a href='"+user_updates[i][0]+"' > post </a></p>"
                                }
                            else if(user_updates[i][2] == "cause")
                                {
                                    html += "<p class='"+class_css+"' onmouseover='mark_as_viewed("+user_updates[i][4]+");'> <span style='float:right'><a href='javascript:void(0)' onclick='delete_update("+user_updates[i][4]+");'>delete</a></span> <br class='clear'/> You can support a <a href='"+user_updates[i][0]+"' > cause </a></p>"
                                }                            
                        }
                    $("#nresults").html(html);
                    $("#sp_count").html(total_updates);
                    
                    
		}
                else
                    {
                        $("#nresults").html('<p>No notifications found</p>');
                    }
	},
        delete_notification: function(result)
        {
            eval(result);
            
        }
}
function mark_as_viewed(id)
{
    if(id != "0" && id != "")
        {
             var u = new markasviewed(markAsViewedHandler)
             u.mark_as_shown(id);
        }
}
var markAsViewedHandler = {

    mark_as_shown: function(result) {
		eval(result);
            }


}
function delete_update(id)
{
     if(id != "0" && id != "")
        {
             var u = new userupdates(userUpdatesHandler)
             u.delete_notification(id);
        }
}
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\n";
}

if (!validatePresent(document.getElementById('username-signup'), 'username-signup-form','true') ) {
		errs += 1; 
		error_fields += String.fromCharCode(8226)+" Please enter a Username\n";
}
if (!validateEmail(document.getElementById('email-signup'), 'email-signup-form','true') ) {
		errs += 1; 
		error_fields += String.fromCharCode(8226)+" Please enter your Email Address\n";
}
if (!validatePresent(document.getElementById('password-signup'), 'password','true') ) {
		errs += 1; 
		error_fields += String.fromCharCode(8226)+" Please enter a Password\n";
}
if (document.getElementById('tandc').checked != true) {
	errs+=1;
	error_fields +=String.fromCharCode(8226)+' Please confirm you have read and agree to our Terms and Conditions\n';
}
if (errs>20)  {
 alert('There are too many fields to list which need correction before continuing:\n');
 document.getElementById('message').innerHTML =error_fields;
} else if (errs>0)  {
 alert('There is information that needs correction before continuing:\n'+error_fields);
}
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 = "";
function containsURL(formId,fid)
{
    form_id = formId;
    var contains = false;
    var search_term = $("#"+fid).val();
    var search_url = search_term.split(" ");
    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();
        $("#"+form_id).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
	});

}
$(document).ready(function(){

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

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

	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup();
		}
	});
    /*  get_latest_updates();
       var user_id=$("#notification_user").val();
       if(user_id && user_id != "0" )
        {
            var holdTheInterval = setInterval(get_latest_updates, 5000);
        }
        */

});
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 showAskFreind(activity_id)
{
    $("#friend_panel_"+activity_id).modal();
}
/* Show current post comments */
function show_post_comments()
{
    $('#post_CommentList').css('display','block');
    $('#post_hideall').css('display','block');
    $('#post_viewall').css('display','none');

}
function hide_post_comments()
{
    $('#post_CommentList').css('display','none');
    $('#post_hideall').css('display','none');
    $('#post_viewall').css('display','block');

}
function notificationShow() {
var val = document.getElementById("ndiv").style.display;
	if(val == "none") {
		document.getElementById("ndiv").style.display ="";
	} else {
		document.getElementById("ndiv").style.display ="none";
	}
}

