// Common JavaScript - Combines code from other js files - JBB 16/1/09


function clientSideInclude(id, url) {
  var req = false;
  // For Safari, Firefox, and other non-MS browsers
  if (window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch (e) {
      req = false;
    }
  } else if (window.ActiveXObject) {
    // For Internet Explorer on Windows
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        req = false;
      }
    }
  }
 var element = document.getElementById(id);
 if (!element) {
  alert("Bad id " + id + "passed to clientSideInclude. \n\nYou need a div or span element with this id in your page.");
  return;
 }
  if (req) {
    // Synchronous request, wait till we have it all
    req.open('GET', url, false);
    req.send(null);
    element.innerHTML = req.responseText;
  } else {
    element.innerHTML =
   "Sorry, your browser does not support the scripts used to properly display this page.\n\n" +
      " This page requires a modern browser (Firefox, Safari, or Internet Explorer 6 or better";
  }
}


function initPage(){

// Setup variable for the cookiename, get the correct cookie
	var receivedCookieData = getCookie("fontsize");
	document.body.style.fontSize=receivedCookieData;
	if(receivedCookieData == null)
	{
		document.body.style.fontSize = '100%';
	}
	
	if ( document['TextDown']  //  if button exists
	  && receivedCookieData == '60%')
	{
		document['TextDown'].src = "/Assets/text_shrink_grey.gif";
		document['TextDown'].alt = "Minimum Size";
	}
	if(document['TextUp']  //  if button exists
	  && receivedCookieData == '140%')
	{
		document['TextUp'].src = "/Assets/text_enlarge_grey.gif";
		document['TextUp'].alt = "Minimum Size";
	}

// do we want light on black?
	receivedCookieData = getCookie("colour");
	if(receivedCookieData == 'neg') setColoursNegative();
	else setColoursPositive();
	
}
//  add trim functionality for strings

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

// cookie functions - Set and return the value of the cookie
function getCookie(c_name) {
	var nameEQ = c_name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = trim(unescape(ca[i]));
		if (c.indexOf(nameEQ) == 0){
//			alert (c);
			return trim(c.substring(nameEQ.length,c.length));
		}
	}
//	alert ("No cookie");
	return null;
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function checkCookie(c_name)
{
getVal=getCookie(c_name);
if ( getVal == null || getVal == "")
  {
  alert('You do not appear to be allowing us to set a cookie on your computer.\n\nWe use a cookie to store your preferences, so when you go to another page it will appear with the standard style rather than the style you have selected.');
  }
//  else {alert(getVal); }
}

//  shrink and grow the text
function SmallerText()
{
	var CurrentSize = "";
	// change size  -  Assume buttons exist
	document['TextUp'].src = "/Assets/text_enlarge.gif";
	document['TextUp'].alt = "Increase font";
	switch(document.body.style.fontSize)
	{
		case '':
		case '100%':
			CurrentSize='80%';
			break;
		case '120%':
			CurrentSize='100%';
			break;
		case '140%':
			CurrentSize='120%';
			break;


		case '80%':
			CurrentSize='60%';
			document['TextDown'].src = "/Assets/text_shrink_grey.gif";
			document['TextDown'].alt = "Minimum Size";
			break;
	}
	if(CurrentSize.length > 0)
	{
		document.body.style.fontSize=CurrentSize;
		setCookie('fontsize',CurrentSize);
		checkCookie('fontsize')
	}
}
function BigText()
{
	var CurrentSize = "";
	// change size - assume buttons exist
	document['TextDown'].alt = "Decrease font";
	document['TextDown'].src = "/Assets/text_shrink.gif";
	switch(document.body.style.fontSize)
	{
		case '60%':
			CurrentSize='80%';
			break;
		case '80%':
			CurrentSize='100%';
			break;
		case '':
		case '100%':
			CurrentSize='120%';
			break;

		case '120%':
			CurrentSize='140%';
			document['TextUp'].src = "/Assets/text_enlarge_grey.gif";
			document['TextUp'].alt = "Maximum Size";
			break;
	}
	if(CurrentSize.length > 0)
	{
		document.body.style.fontSize=CurrentSize;
		setCookie('fontsize',CurrentSize);
		checkCookie('fontsize')
	}
}   
function setColoursNegative()
{
	document.body.className = 'JBB_BodyNeg';
	if (document.getElementById('colourFlipper')){
		document.getElementById('colourFlipper').innerHTML = 'Dark on Light';
	}
}
function setColoursPositive()
{
	document.body.className = 'JBB_Body';
	if (document.getElementById('colourFlipper')){
		document.getElementById('colourFlipper').innerHTML = 'Light on Dark';
	}
}
function flipColours(thisLink)
{
		if (document.body.className == 'JBB_BodyNeg')
		{	document.body.className = 'JBB_Body'
			setCookie('colour','pos');
			checkCookie('colour');
			thisLink.innerHTML = 'Light on Dark';
		}
		else 
		{	document.body.className = 'JBB_BodyNeg'
			setCookie('colour','neg');
			checkCookie('colour');
			thisLink.innerHTML = 'Dark on Light';
		}
}

//  From TitleCase


function title_case() {
    var temp_string = this.toLowerCase()
    var left_string
    var right_string
    var new_letter
    
    // Make the first character uppercase
    var first_char = temp_string.left(1).toUpperCase()
    temp_string = first_char + temp_string.substring(1)
    
    // Get the position of the first space
    var space_location = temp_string.indexOf(" ")
    
    // Loop until there are no more spaces
    while (space_location != -1) {
        
        // Get the part up to and including the current space
        left_string = temp_string.left(space_location + 1)
        
        // Get the first letter of the next word and convert it to uppercase
        new_letter = temp_string.charAt(space_location + 1).toUpperCase()
        
        // Get the rest of the string after that letter
        right_string = temp_string.right(temp_string.length - space_location - 2)
        
        // Put it all together
        temp_string = left_string + new_letter + right_string
        
        // Get the next space
        space_location = temp_string.indexOf(" ", space_location + 1)
    }
    return temp_string   

}

function extract_left(total_chars) {
    return this.substring(0, total_chars)
}

function extract_right(total_chars) {
    return this.substring(this.length - total_chars)
}

String.prototype.right = extract_right
String.prototype.left = extract_left
String.prototype.toTitleCase = title_case


//  from ValidateDate

function check_date(DateField)
{
	
//  updated JBB 21/9/07 - 8/10/07
//  Investigating why 2 digit year does not work
//  extensive comments added and order revised
//  in fact, totally rewritten!

var checkstr = "0123456789";
var checkSeperator = "/ -.";  //  valid seperators on input
var validChars = checkstr + checkSeperator
var seperator = "/"; //  used on output string
var DateValue = "";
var DateTemp = "";
var leap = 0;
var noSeperators = 0;
var day_slice;
var month_slice;
var year_slice;
var i;
var minYear = 1800;  //  earliest valid year

DateValue = DateField.value;

if (DateValue.length == 0){
//  assume a blank date will be picked up elsewhere
	return true;
}
// Check for invalid characters - valid are 0 - 9, ./- and space
for (i = 0; i < DateValue.length; i++) {
	  if (validChars.indexOf(DateValue.substr(i,1)) == -1) {
		 
		 return errorReport( 43, DateField);
	  }
}
//  check there are enough characters
if (DateValue.length < 6){
	 return errorReport( 44, DateField);
}

//  Valid formats are dd/mm/yy dd.mm.yy (or other seperators shown here)
//  or with 4 character year dd-mm-yyyy
//  or no separator ddmmyy or ddmmyyyy
//  to make this work we start by seeing if there are any seperators

var last_seperator = 0;

//  Find part before first seperator (days)
for (i = 0; i < DateValue.length; i++) {
  if (checkSeperator.indexOf(DateValue.substr(i,1)) >= 0) {
			 day_slice = DateValue.substr(0,i);
			 last_seperator = i;
			 break;
	 }
}

//  if no separators, set flag
if (i >= DateValue.length){
	noSeperators = 1;
}
else //  get next slice (month)
{	//  counter for number of characters in month
	var occur_count = 1;
	// find part between separators (month)
	for (i = last_seperator + 1; i < DateValue.length; i++) {
	  if (checkSeperator.indexOf(DateValue.substr(i,1)) >= 0) {
		  if (i == last_seperator + occur_count){
				 occur_count = occur_count + 1;
		  }else{
				 month_slice = DateValue.substr(last_seperator + occur_count,i - (last_seperator + occur_count));
				 last_seperator = i;
				 break;
		  }
	  }
	}
	//  if not enough characters, set flag
	if (i >= DateValue.length){
		noSeperators = 2;
	} 
	else
	{//  we have day and month so get year
		for (i = last_seperator + 1; i < DateValue.length; i++) 
		{
			if (checkSeperator.indexOf(DateValue.substr(i,1)) >= 0) {
				noSeperators = 3; // error - too many seperators
			}
		}
		year_slice = DateValue.substr(last_seperator + 1,(DateValue.length - (last_seperator + 1)));
	}
}
if (noSeperators == 0)
{  //  we have day month and year slices
	
	if (day_slice.length == 0 || day_slice.length > 2){
				return errorReport(101, DateField);
	}
	
	if (month_slice.length == 0 || month_slice.length > 2){
				return errorReport(102, DateField);
	}
	if (day_slice.length == 1){
		day_slice = "0" + day_slice;
	}
	if (month_slice.length == 1){
		month_slice = "0" + month_slice;
	}
}
else  //  wrong number of seperators
{
	DateValue = DateField.value;  //  start again
	// Delete all chars except 0..9 
	for (i = 0; i < DateValue.length; i++) {
		  if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
			 DateTemp = DateTemp + DateValue.substr(i,1);
		  }
	}
	DateValue = DateTemp;

	if(DateValue.length < 6){
				return errorReport(18, DateField);
	}
	day_slice = DateValue.substr(0,2);
	month_slice = DateValue.substr(2,2);
	year_slice = DateValue.substr(4);  //  just take the rest of the line
}
//  we have the slices, now validate them	
	
if (year_slice.length < 2 || year_slice.length == 3 || year_slice.length > 4){
			return errorReport(103, DateField);
}
// if year is entered as 2-digit  assume 20xx 
if (year_slice < 100){
	year_slice = '20' + year_slice;
}
if (year_slice < minYear){
			return errorReport(27, DateField);
}
/* Validation of month*/
if ((month_slice < 1) || (month_slice > 12)) {
			return errorReport(21, DateField);
}
 /* Validation of day*/
if (day_slice < 1) {
			return errorReport(22, DateField);
}
/* Validation leap-year / february / day */
if ((year_slice % 4 == 0) && ((year_slice % 100 != 0) || (year_slice % 400 == 0))) {
	  leap = 1;
}
if (month_slice == '02'){
	 if (leap == 1 && day_slice > 29) {
			return errorReport(23, DateField);	 }
	 if (leap != 1 && day_slice > 28) {
			return errorReport(24, DateField);	}
}
else 
{
	if ((month_slice == "04") || (month_slice == "06") || (month_slice == "09") || (month_slice == "11"))
	{
		if (day_slice > 30) {
			return errorReport(26, DateField);
		}
	}
	else
	{
		if (day_slice > 31) {
			return errorReport(25, DateField);
		}
	}
}

	/* if no error, write the completed date to Input-Field */
DateField.value = day_slice + seperator + month_slice + seperator + year_slice;
return true;

}

function errorReport( errCode, DateField)
{
var errmsg;

switch(errCode)
{
case 43:
  errmsg = 'Invalid characters entered in date - please use DD/MM/YYYY format';
  break;
case 44:
  errmsg = 'Date entered is too short - min 6 characters (D/M/YY)';
  break;
case 18:
  errmsg = 'Invalid format used - please use DD/MM/YYYY';
  break;
case 27:
  errmsg = 'Invalid year entered - must be after ' + minYear;
  break;
case 20:
  errmsg = 'The date contains an invalid year value';
  break;
case 21:
  errmsg = 'Invalid value entered for the month';
  break;
case 22:
  errmsg = 'Cannot have a day value of less than 1';
  break;
case 23:
  errmsg = 'This is a leap year. You can only have a maximum of 29 days in February';
  break;
case 24:
  errmsg = 'This is not a leap year. You can only have a maximum of 28 days in February';
  break;
case 25:
  errmsg = 'The specified month only has 31 days in it';
  break;
case 26:
  errmsg = 'The specified month only has 30 days in it';
  break;
case 101:
  errmsg = 'Please enter the day as one or two digits i.e. D or DD';
  break;
case 102:
  errmsg = 'please enter the month as one or two digits i.e. M or MM';
  break;
case 103:
  errmsg = 'please enter the year as two or four digits i.e. YY or YYYY';
  break;
case 104:
  errmsg = '';
  break;
case 10:
  errmsg = '';
  break;
default:
  errmsg = 'Unidentified Error - Code ' + toString(errCode);
}
alert(errmsg);
DateField.focus();
DateField.select();
DateField.className="errorfield";
return false;

}

