

/*
 * File: standard.js
 * Include with: <script SRC="js/standard.js"></script>
*/

function MM_openBrWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}


function openWin(url,width,height){
	var this_url = url;
	var arg = "width=" + width + ",height=" + height + ",toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes";
	window.open(this_url,'child',arg);
}

function openStrippedWin(url,width,height) {
	var this_url = url;
	var arg = "width=" + width + ",height=" + height + ",status=no,toolbar=no,menubar=no,scrollbars=no,resizable=yes";
	window.open(this_url,'child',arg);
}

function openWinArgs(url,arg){ // not used or tested yet.
	var this_url = url;
	var this_arg = arg;
	window.open(this_url,'child',this_arg);
}

function closeWin()	{
//  NB - user receives Warning Message if the current window wasn't opened by a parent browser window
//  adapt URL and uncomment following line if you want to select parent window's URL
//	window.opener.location = "http://jnewton9.valuehost.co.uk/sereno/client_page.php";
	this.window.close();
}

// A utility function that returns true if a string contains only
// whitespace characters.
function isblank(s)
{
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

// Delete any spaces from string
function stripSpaces(s)
{
	str = s.replace( /\s/g, "" );
	return str;
}

// Delete apostrophe from a string
function stripApostrophe(s)
{
	str = s.replace('\'', "");
	return str;
}

// Removes first chars from string
// s = string to remove prefix from, n is no of chars to strip from string
function stripPrefixAndUnderscore(s, n)
{
	noRemove = n;
	stripped = s.substring(n,s.length);
	str = stripped.replace(/_/, " ");
	str2= str.replace(/_/, " "); // this should be in a loop, really. Currently, just takes out up to 2 underscores...
	return str2;
}

// If there is a form on the page, it's first element is given the focus
// Calling HTML: - <BODY onLoad="firstFocus()"> 
function firstFocus()
{
   if (document.forms.length > 0)
   {
      var TForm = document.forms[0];
      for (i=0;i<TForm.length;i++)
      {
         if ((TForm.elements[i].type=="text")||
           (TForm.elements[i].type=="textarea")||
           (TForm.elements[i].type.toString().charAt(0)=="s"))
         {
            document.forms[0].elements[i].focus();
            break;
         }
      }
   }
}

// see if a checkbox is ticked or not
function checkboxClicked( box ){
    if( box.checked ){
        return true;
    }
    else{
        return false;
    }
}

// check for a valid email address.
function checkEmail(email) {
    for(var i = 0; i < email.length; i++) { // check it's not blank
        var c = email.charAt(i);
        if ((c == ' ') && (c == '\n') && (c == '\t')){
			return false;
		}
    }	
	var filter  = /^([a-zA-Z\'0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	if (filter.test(email)) {
		return true;
	}
	else {
		return false;
	}
}

// Detects if enter is pressed, and submits the form if it is.
// Allows calling HTML to specify which form on a page to submit.
// Calling HTML in final form element on page, where 'frmClientLogin' is the name of the form:- <input type="password" name="txtPassword" onKeyPress="return checkEnterToSubmit(event, 'frmClientLogin', true)" />
function checkEnterToSubmit(event, formname, checkAll)
{ 
	var chkAll = checkAll;
	var frm = formname;	
	var code = 0;
		code = event.keyCode;
	if (code==13)
		submitForm(frm,false,chkAll);
}

// checks form using the 'verify' function, then submits.
// if checkAll=true, then all text boxes must be filled in.
function submitForm(formname, checkAll){

	var frmname = formname;
	var chkAll = checkAll;
	var frm = "document." + frmname;

    if (chkAll==true){ // if the form needs to have entries in all fields

		if (verify(eval(frm))){ // check the form fields for entries
		   eval(frm).submit();
		   return true;
		}
		else { // 'verify' function says not all fields are complete
		   return;
		} 

    }
    else { // not all fields in the form need to be complete
 	  eval(frm).submit();
	  return true;
    } // end 'if (chkAll...'
}

// This is the function that performs form verification.
// Checks any text or text area element against pre-defined 
// 'optional', 'max' and 'min' properties.
// Doesn't do radio buttons or check boxes.
// NB - 'max' and 'min' refer to NUMERIC values.
// NB - calls stripPrefixAndUnderscore to remove first 3 chars of field name - eg txtSurname -> Surname
function verify(f)
{
    var msg;
    var empty_fields = "";
    var errors = "";
    // Loop through the elements of the form, looking for all
    // text and textarea elements that don't have an "optional" property
    // defined. Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,
    // then verify that they are numbers and that they are in the right range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        if (((e.type == "text") || (e.type == "textarea") || (e.type == "password")) && !e.optional) {
            // first check if the field is empty
            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "\n          " + stripPrefixAndUnderscore(e.name,3);
                continue;
            }
            // Now check for fields that are supposed to be numeric.
            if (e.numeric || (e.min != null) || (e.max != null)) {
                var v = parseFloat(e.value);
                if (isNaN(v) ||
                    ((e.min != null) && (v < e.min)) ||
                    ((e.max != null) && (v > e.max))) {
                    errors += "- The field " + stripPrefixAndUnderscore(e.name) + " must be a number";
                    if (e.min != null)
                        errors += " that is greater than " + e.min;
                    if (e.max != null && e.min != null)
                        errors += " and less than " + e.max;
                    else if (e.max != null)
                        errors += " that is less than " + e.max;
                    errors += ".\n";
                }
            }
        }
    }
    // Now, if there were any errors, display the messages, and
    // return false to prevent the form from being submitted.
    // Otherwise return true.
    if (!empty_fields && !errors) return true;
    msg  = "_________________________________\n\n"
    msg += "Your form is not quite complete.\n\n";
//    msg += "Please sort out the issues below and try again:\n";
//    msg += "_________________________________\n\n"
    if (empty_fields) {
        msg += "The following required field(s) are empty:"
                + empty_fields + "\n";
        if (errors) msg += "\n";
    }
    msg += errors;
    alert(msg);
    return false;
}

/*
This function takes args to check the delete link which has been clicked
was intended, then forwarding the user to the delete function if OK is clicked:

delete_code	= the db code which is to be deleted.
delete_item	= just a text descr. for alert message - what kind of item? eg 'tutor'
pg_to		= where is the delete process to take place? Name of PHP page
qryst_extension= other params to be fed to next page following the redirect.
*/

function confirm_delete(delete_code,delete_item,pg_to,qrystr) {
	
	// CONFIRM REQUIRES ONE ARGUMENT
	var message = "Are you sure that you want\nto delete this " + delete_item + '?';

	// CONFIRM IS BOOLEAN. THAT MEANS THAT
	// IT RETURNS TRUE IF 'OK' IS CLICKED
	// OTHERWISE IT RETURN FALSE
	var return_value = confirm(message);

	// TEST TO SEE IF TRUE|FALSE RETURNED
	if (return_value == true) {
		// YOUR 'OK' SCRIPT GOES HERE
		window.location = pg_to + "?dlt=" + delete_code + qrystr;
	} else {
		return ;
	}
	return;
}

/*
This function takes args to prompt the user with a message and then
forward the user to another page if OK is clicked:

message_text = the prompt message to be displayed
Forward_to = name of the php page to forward to if OK is clicked including any query string
*/

function prompt_user(message_text,forward_to) {
	
	// CONFIRM REQUIRES ONE ARGUMENT
	var message = message_text;

	// CONFIRM IS BOOLEAN. THAT MEANS THAT
	// IT RETURNS TRUE IF 'OK' IS CLICKED
	// OTHERWISE IT RETURN FALSE
	var return_value = confirm(message);

	// TEST TO SEE IF TRUE|FALSE RETURNED
	if (return_value == true) {
		window.location = forward_to;
	} else {
		return ;
	}
	return;
}

// for development - generate an alert box.
function underDevelopment(){
	alert('This feature is currently under \ndevelopment by Sereno.');
}

// rollover a table row and change its colour
// eg of use: 		  <tr bgcolor='<?=$colour?>' onclick="window.location.href='job.php?expand=<?=$this_job_code?>';" onmouseover="do_over(this,'<?=$colourOver?>');" onmouseout="do_over(this,'<?=$colour?>');" style="">
function do_over(obj,colour) {
	 obj.style.backgroundColor = colour; obj.style.color = 'black'; obj.style.cursor = 'hand'; obj.style.title = 'Ha Ha';
}

function do_out(obj) {
	obj.style.backgroundColor = ''; obj.style.color = '';
}

// Macromedia functions for image rollover manipulation.
function MM_swapRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

// Set css //
function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
function confirm_message(message,pg_to,query_string) {
	
	// Check whether the message is confirmed by the user
	var return_value = confirm(message);

	// if yes (true) then route to new page
	if (return_value == true) {
		// add query string if present
		if (query_string.length>0) {
			pg_to = pg_to + "?" + query_string;
			}
		window.location = pg_to;
	}
	return;
}

/*
Used to log out of current window. Used in administrative screens.
*/
function closeWindow() {
	
	// CONFIRM REQUIRES ONE ARGUMENT
	var message = "Are you sure that you want\nto close this window?";
	var return_value = confirm(message);

	// TEST TO SEE IF TRUE|FALSE RETURNED
	if (return_value == true) {
		// YOUR 'OK' SCRIPT GOES HERE
		window.close();
		return ;
	}
	return;
}

window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
