/* GUEST BOOK JS INTERFACE */

/* See http://gr0w.com/articles/code/ajax_vs_rpc_javascript_with_livesearch_example/ 
	   http://www.activewidgets.com/javascript.forum.4257.38/javascript-and-php-variables.html
	   http://www.phpied.com/javascript-include/
*/
var head,scrNum=0,rpc_url="http://www.chrispower.co.uk/gb/rpc.php", // must give full path, not just rpc.php 
	sep ="|";

var ptr=0,		// Points to the next table entry. Act as a session variable, sent to the server where it is
				// incremented and tested in PHP function view_comment(). The ONE exception is the add_comment_cb(),
				// so the last add, which appears first can be seen
range=8,		// How many table entries to bring back
newcode="",		// Returned from server, text value of graphic string, creat by PHP rand_str()
mytitle = document.title;

// based on  http://www.phpied.com/javascript-include/ Note the issues mentioned with IE
// sig Says: October 6th, 2005 at 4:38 am
// Note the issues mentioned with IE
var js_node;
function do_sql(info) {
    // script_filename += '?' + Math.random(0, 1000) + '=' + Math.random(0, 1000);
	var script_filename=rpc_url + "?" + "info=" + info + "&" + "script_id=" + Math.random(0, 1000);
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    if (js_node)
    {
       html_doc.replaceChild(js,js_node);
    }
    else
    {
       html_doc.appendChild(js);
    }
    js_node = js;
    return false;
}

/*
// old method from http://gr0w.com/articles/code/ajax_vs_rpc_javascript_with_livesearch_example/ works well needs a removescript function
function do_sql(info)
{	head=document.getElementsByTagName('head').item(0);
	script=document.createElement('script');
	script.id='scr'+scrNum;
	// Create a path to the server and params peg, site_name and script_id ( required by function removeScript(scriptid) )
	script.src=rpc_url + "?" + "info=" + info + "&" + "script_id=" + script.id;	// alert(script.src); // return;
	script.type='text/javascript';
	script.defer=true;
	scrNum++;
	void(head.appendChild(script));
}


function removeScript(scriptid){	// called dynamically when PHP script "calls" it
	var d=document;
	var old=document.getElementById(scriptid);
 	if(old){head.removeChild(old);}
}

*/

function myrand() {return Math.round(10000*Math.random());}

var d='<span id="myview">My View</span>';

function simple_check(myname,myemail,mycomment){
	function isValidEmail(str) { return (str.indexOf(".") > 2) && (str.indexOf("@") > 0); } 
	
	var err="";
    if (myname.length < 3)		err += "Name Required\n";
    if (mycomment.length < 4)	err += "Comment Required\n";
    // email can be none or valid address.
    if (myemail != "none"){ if (!isValidEmail(myemail))	err += "Email Address " + myemail + " Seems Wrong\n";}
	return err;
}

function id_chk(my_id){	// required for standard guess book id's
	var ret_val=null;
	try{
		ret_val=document.getElementById(my_id).value ;
	}
	catch(err){
		alert("Form Error " + my_id + " Expected " + err );
	}	
	return ret_val;
}

/* ******************************************* ADD ******************************************* */
function add_comment(){
	/* This checking ensures that new guest books (the html part) has correct form ids */
	var myname=id_chk("myname");
	if (myname==null) return;
	
	var myemail=id_chk("myemail");
	if (myemail==null) return;
	
	var mycomment=id_chk("mycomment");
	if (mycomment==null) return;
	
	var mycode=id_chk("mycode");
	if (mycode==null) return;

	// alert("Name = " + myname + " Mail = " + myemail + " Comment = " + mycomment + " Code = " + mycode ); return;
	
	if(mycode != newcode){alert("Captcha code = " + newcode + " Typed code = " + mycode); return;}
	
	if(myemail=="")	myemail="none";		// Make a blank email a definite a none, an empty string gets misinterpreted going thru js->php->js
	var check = simple_check(myname,myemail,mycomment);
	if ( check != "" ) {alert(check); return};
    
	// Crude filtering. Anything in the regexp is permitted else replaced by a space
	myname=myname.replace(/[^A-Za-z0-9\-\']+/g," ");    // 
	mycomment=mycomment.replace(/[^A-Za-z0-9\.\,\?\!\(\)\:\'\" ]+/g,"");	

	var add_data='add'+sep+myname+sep+myemail+sep+mycomment+sep+mytitle;
	do_sql(add_data);
}

function add_comment_cb(z){
    if (z!="OK"){ 
		alert(z); 
	}else{
		ptr=0;				// viewing pointer now needs resetting, unintelligent way set to beginning
		view_comment(); 
	}
}
/* ******************************************* DEL ******************************************* */
function del_comment()
{	var a = new Array();									// temp array where ticked checkboxes are are saved
	var items = document.getElementsByTagName("input");		// number of <input type='checkbox' value=$i />
	for (var i = 0; i < items.length; i++){
		if ( (items[i].checked) && (items[i].name == 'mylist') )
			a.push(items[i].value);							// saved ticked boxes
	}
	if (a.length == 0){										// if none ticked then don't go on
		alert("No entries ticked");
		return;
	}
 	var del_list=a.join(",");								// format a coma seperated list of items to be deleted										
	var pass = document.getElementById("password").value;	// pickup the password
	
	var del_data='del'+sep+del_list+sep+pass+sep+mytitle;
	// alert(del_data);
	do_sql(del_data);
}

function del_comment_cb(z){
    if (z!="OK"){ 
		alert(z); 
	}else{
		ptr=0;				// viewing pointer now needs resetting, unintelligent way set to beginning
		view_comment(); 
	}
}	
/* ******************************************* VIEW ******************************************* */
function view_comment(){
	// action|data.......
	var view_data = "view" + sep + ptr + sep + range + sep + mytitle;
	// alert(view_data); // return;
	do_sql(view_data);
}

function view_comment_cb(z){
	var a=z.split("|");
	// alert(a[3]);
	document.getElementById('myview').innerHTML=a[0];
	ptr=a[1];
	newcode=a[3];
	var r=Math.floor(Math.random()*1001);		// because IE displays cached image (image name stays the same but content changes by GD in PHP)
	document.getElementById("bk_bg0").innerHTML = "<img width='65' src='http://chrispower.co.uk/gb/new.png?state=" + r + "'>"; // "<img width='65' src='new.png'>";

	//alert(ptr + " " + a[2] + " " +a[3] + " " + a[4] + " " + newcode);
	// next are for debug/testing. the test incase the ID's are missing in the html (IE)
	var ID=document.getElementById("ptr");
	if(ID!=null) ID.innerHTML = "Ptr = " + ptr;
	var ID=document.getElementById("list");
	if(ID!=null) ID.innerHTML = "Captcha = " + a[3];
	var ID=document.getElementById("tot");
	if(ID!=null) ID.innerHTML = "Total = " + a[2];
}
