//***********************************************************************************
//* GENERAL.JS - Contains all javascript functions for codsalldramaticsociety.co.uk *
//***********************************************************************************
//*                                  RELEASE HISTORY                                *
//***********************************************************************************
//* Version    Date     Reason for Release                                  Author  *
//* ~~~~~~~  ~~~~~~~~   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   ~~~~~~~~~ *
//*  1.00    04/12/06   Original Release                                  C.P. Hale *
//*  1.01    16/01/07   Global variables added for ticket values.         C.P. Hale *                                                                               *
//***********************************************************************************

//********************************************************************************
//* Works out remaining characters as characters added to text area.(UNTESTED)   *
//*   inputValue - max characters available.                                     *
//*   Returns remaining characters.                                              *
//* NOTE - Use the onKeyUp method with this function.                            *
//********************************************************************************
function remainingchars(maxchars) {
var remainder = 0
alert(toString(maxchars))
remainder=toString(maxchars - document.email.message.length)
alert(toString(remainder))
return remainder
}

//********************************************************************************
//* Calculates the number of tickets required for play (standard + concession).  *
//*   stdtkt - Number of standard price tickets required.                        *
//*   contkt - Number of concessionary price tickets required.                   *
//*   Returns number of tickets required (integer value).                        *
//********************************************************************************
function calcnumplaytickets(stdtkt,contkt) {
  var ticketresult = parseInt(stdtkt,10) + parseInt(contkt,10)
  return ticketresult
}

function setprice(datestring, stdtickets,contickets) {
var retval = 0.00
matchstr = new Array("Please select...")
	if(datestring != matchstr) {
		matchstr = Array("14:30 Saturday 15th March 2008")
		if (datestring == matchstr) {
		    retval=parseFloat(contickets)  // Return concession price value.
		}
		else {
		   retval=parseFloat(stdtickets)  // Return standard prive value.
		}
	}
return retval
}

//********************************************************************************
//* Adds two integers together and returns the result and adds leading and       *
//* trailing zeros as required.                                                  *
//********************************************************************************
function addvalues(val1, val2) {
var costresult = parseInt(val1,10) + parseInt(val2,10)
var costtest = costresult % 1
if(costtest != 0) { 		// Is result an integer?
    costresult += "0" 		// No, add "0" to result
}
else {
    costresult += ".00" // Yes, add ".00" to result
}
return costresult
}

//********************************************************************************
//* Converts total cost and adds leading and trailing zeros as required.         *
//*   totalcostresult    - total cost as a raw floating value.                   *
//*   Returns total cost (floating point value).                                 *
//********************************************************************************
function converttotal(totalcostresult) {
var costresult = parseFloat(totalcostresult)
var costtest = costresult % 1
if(costtest != 0) { 		// Is result an integer?
    costresult += "0" 		// No, add "0" to result
}
else {
    costresult += ".00" // Yes, add ".00" to result
}
  return costresult
}

//********************************************************************************
//* Calculates the total cost of tickets required for play.                      *
//*   stdtickets - Number of standard price tickets required.                    *
//*   contickets - Number of concessionary price tickets required.               *
//*   stdval     - Cost of a standard ticket.                                    *
//*   conval     - Cost of a concessionary ticket.                               *
//*   Returns total cost (floating point value).                                 *
//********************************************************************************
function calctotalplaycost(stdtickets,contickets,stdval,conval) {
var costresult = parseFloat((parseInt(stdtickets,10) * stdval)+(parseInt(contickets,10) * conval))
var costtest = costresult % 1
  if(costtest != 0) { 		// Is result an integer?
    costresult += "0" 		// No, add "0" to result
  }
  else {
    costresult += ".00" // Yes, add ".00" to result
  }
  return costresult
}

//********************************************************************************
//* Checks if a text field is empty or not.                                      *
//*   inputValue - Value to be tested.                                           *
//*   Returns true if okay, or false if there's an error.                        *
//********************************************************************************
function exists(inputValue) {
  var aCharExists = false	
  for (var i=0; i<=inputValue.length; i++) {
    if (inputValue.charAt(i) != " " && inputValue.charAt(i) != "") {
      aCharExists = true
      break
    }
  }
  return aCharExists
}

//********************************************************************************
//* Checks if email address is valid.                                            *
//*                                                                              *
//* Email Address format: <aaa.>bbb@domainname.aaa<.aaa>                         *
//*   Optional characters are shown between < and >.                             *
//*                                                                              *
//* The first character of the string & the first character directly after the   *
//* dot's and the '@' (which must be present) must be an alpha (a to z).         *
//* Although, the search for the first and third dots look superfluous, as they  *
//* are not always present. You still need to check that the first character     *
//* that follows them is valid when they ARE present.                            *
//*                                                                              *
//*   estr - String containing email address to be validated.                    *
//*   Returns true if okay, or false if there's an error.                        *
//********************************************************************************
function isValidEmail(estr) {
var index = 0     // Current position in string.
var len = 0       // Length of the string.
var numAts = 0    // Counts the number of @ characters found (should only be one).
var atpos = 0     // Index of '@' when found (must be present).
var dot1pos = 0   // Index of the first . in string (if present).
var dot2pos = 0   // Index of the second . in string (must be present).
var dot3pos = 0   // Index of the third . in string (if present).
var result = true // Result for return (false = invalid email address format).

  len = estr.length  // Get the length of the string.
  if (!isAlpha(estr.charCodeAt(0))) { // Check 1st. char. is a letter.
    result = false           // If not, set result to false.
  }
  else { // Find the '@' (There must be one).
    while(index < len && numAts <= 1) {
      if(estr.charAt(index) == '@') {
        atpos = index // When found assign current index value to atpos.
        numAts++
      }  
    index++ // Next position.
    }
    if (!isAlpha(estr.charCodeAt(atpos + 1))) { // Check char after @ is alpha.
      result = false            // If not, set result to false.
    }

// Find 1st. dot (if used).
    index = 0; // Begin at the start of the string.
    while((index <= atpos) && !dot1pos && (result == true)) { // Search up to the @ index.
      if(estr.charAt(index) == '.') {
        dot1pos = index
        break;
      }
    index++ // Next position.
    }
    if (dot1pos > 0) {
      if (!isAlpha(estr.charCodeAt(index + 1))) { // Check char after 1st . is alpha (if present).
        result = false            // If not, set result to FALSE.
      }
    }
// Find 2nd. dot (must be present).
    while(((atpos + 1) <= len) && !dot2pos && (result == true)) {
      if(estr.charAt(index) == '.') {
        dot2pos = index
        break;
      }
    index++ // Next position.
    }
    if (!isAlpha(estr.charCodeAt(index + 1))) { // Check char after 2nd . is alpha (must be present).
      result = false             // If not, set result to FALSE.
    }
// Find 3rd. dot (if present).
    while(((atpos + 1) <= len) && (dot3pos == false) && (result == true)) {
      if(estr.charAt(index) == '.') {
        dot3pos = index
        break;
      }
    index++ // Next position.
    }
  if(dot3pos > 0) {
    if (!isAlpha(estr.charCodeAt(index + 1))) { // Check char after 3rd . is alpha (if present).
      result = false             // If not, set result to FALSE.
    }
  }
// If no @ was found then atpos will be zero. If no dot was found after the @ then
// dot2pos will be zero. More than one @ will cause the result to be false. 
    if ((!atpos) || (!dot2pos) || (numAts >= 2)) {
      result = false
    }
  }
  return result
}

//********************************************************************************
//* Tests if character is an alpha (a to z or A to Z).                           *
//*   inputValue - Variable holding character to be tested.                      *
//*   Returns true if Alpha character, and false if non-Alpha character.         *
//********************************************************************************
function isAlpha(inputValue) {
var testresult = false // Returns the result (true or false).
  if ((inputValue >= 65 && inputValue <= 90) || (inputValue >= 97 && inputValue <= 122)) {
    testresult = true // If inputValue is between 'a' to 'z' and 'A' to 'Z', then okay.
  }
  else {
    testresult = false // Otherwise, it isn't an alpha (letter).
  }
  return testresult
}

//********************************************************************************
//* Cookie functions - DO NOT MODIFY!                                            *
//********************************************************************************
//* "Internal" function to return the decoded value of a cookie                  *
//********************************************************************************
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr== -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

//********************************************************************************
//* Function to correct for 2.x Mac date bug. Call this function to              *
//* fix a date object prior to passing it to setCookie.                          *
//* IMPORTANT: This function should only be called *once* for any given date     *
//*            object!                                                           *
//********************************************************************************
function fixCookieDate (date) {
  var base = new Date(0);
  var skew = base.getTime(); // Dawn of (unix) time - should be 0
  if (skew > 0) // Except on the Mac - ahead of it's time
    date.setTime (date.getTime() - skew);
}

//********************************************************************************
//* Function to return the value of the cookie specified by "name".              *
//*  name - String object containing the cookie name.                            *
//*  returns - String object containing the cookie value, or null if the cookie  *
//*            the cookie does not exist.                                        *
//********************************************************************************
function getCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring( i, j ) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0 ) break;
  }
  return null;
}

//********************************************************************************
//* Function to create or update a cookie.                                       *
//*  name - String object containing the cookie name.                            *
//*  value - String object containing the cookie value. May contain any valid    *
//*    string characters.                                                        *
//*  [expires] - Date object containing the expiration data of the cookie. If    *
//*    omitted or null, expires the cookie at the end of the current session.    *
//*  [path] - String object indicating the path for which the cookie is valid.   *
//*    If omitted or null, uses the path of the calling document.                *
//*  [domain] - String object indicating the domain for which the cookie is      *
//*    valid. If omitted or null, uses the domain of the calling document.       *
//*  [secure] - Boolean (true/false) value indicating whether cookie             *
//*    transmission requires a secure channel (HTTPS).                           *
//*                                                                              *
//* The first two parameters are required. The others, if supplied, must be      *
//* passed in the order listed above. To omit an unused optional field, use null *
//* as a place holder. For example, to call setCookie using name, value and path *            
//* you would code:                                                              *
//*                                                                              *
//*       setCookie ("myCookieName", "myCookieValue", nul, "/");                 *
//*                                                                              *
//*  Note that trailing omitted parameters do not require a placeholder.         *
//********************************************************************************
function setCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) + 
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    (( path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

//********************************************************************************
//* Function to delete a cookie. (Sets expiration date to start of epoch)        *
//*  name -    String object containing the cookie name.                         *
//*  path -    String object containing the path of the cookie to delete. This   *
//*            MUST be the same as the path used to create the cookie, or        *
//*            null/omitted if no path was specified when creating the cookie.   *
//*  domain -  String object containing the domain of the cookie to delete. This *
//*            MUST be the same as the domain used to create the cookie, or      *
//*            null/omitted if no domain was specified when creating the cookie. *
//********************************************************************************
function deleteCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}