var submitted = false;

function submitForm()
{
    if(!submitted)
    {
        document.forms[0].submit();
        submitted = true;
    }
}

function setFocus(id)
{
    document.getElementById(id).focus();
}

function isEmpty(value)
{
    return (value == null || trim(value).length == 0);
}

function isEmptyById(id)
{
    return isEmpty(getFieldValue(id));
}

function setFieldValue(field_id, field_value)
{
    document.getElementById(field_id).value = field_value;
}

function isHiddenById(id)
{
    return isHidden(document.getElementById(id));
}

function isHidden(object)
{
    return(object.style.visibility != 'hidden' && object.style.display != 'none');
}

function isWholeNumber(number)
{
    var result = false;
    if (number.indexOf('.') < 0)
        result = true;
    return result;
}

function getFieldValue(field_id)
{
    return document.getElementById(field_id).value;
}

function getFieldChecked(field_id)
{
    return document.getElementById(field_id).checked;
}

function toggle(id, type)
{
    object = document.getElementById(id);
    display = object.style.display;
    if(type == null)
        type = "block";
    object.style.display = (display == "none" ? type : "none");
}

function uncheckInput(id)
{
    document.getElementById(id).checked = false;
}

function getSumOfFields(fields)
{
    sum = 0;
    for(i = 0; i < fields.size; i++)
    {
        sum += parseFloat(getFieldValue(fields[i]));
    }
    return sum;
}

//Set todays date and time as defaults
function todayDate(){
    var d = new Date();
    var today = d.getDate();
    var month = d.getMonth() + 1;

    //Validate Date
    if(today < 10 )
    today = '0' + d.getDate();

    if(month < 10 )
    today += '/0';
    else
    today += '/';

    today += d.getMonth() + 1;
    today += '/' + d.getFullYear();

    //set dates
    document.forms[0].datefrom.value = today;
    document.forms[0].dateto.value = today;
}

function checkDateById(id)
{
    return check_date(document.getElementById(id));
}

function check_date(field) {

    var checkstr = "0123456789";
    var DateField = field;
    var Datevalue = "";
    var DateTemp = "";
    var seperator = "/";
    var day;
    var month;
    var year;
    var err = 0;
    var i;
    var isLeapYear = false;

    err = 0;

    DateValue = DateField.value;

    // Translate from American format (yyyy/mm/dd)
    if (DateValue.length == 10 && DateValue.substr(4,1) == "/" && DateValue.substr(7,1) == "/") {
        var DateTemp2 = DateValue.substr(8,2) + DateValue.substr(5,2) + DateValue.substr(0,4);
        DateValue = DateTemp2;
    }


    /* 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;


    /* Always change date to 8 digits - string*/
    /* if year is entered as 2-digit / always assume 20xx */
    if (DateValue.length == 6) {
        DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2);
    }

    year = DateValue.substr(4,4);
    month = DateValue.substr(2,2);
    day = DateValue.substr(0,2);
    isLeapYear = (year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0);

    if (DateValue.length != 8) {
        err = 19;
    }
    /* year is wrong if year = 0000 */
    else if (year == 0) {
        err = 20;
    }
    /* Validation of month*/
    else if ((month < 1) || (month > 12)) {
        err = 21;
    }
    /* Validation of day*/
    else if (day < 1) {
        err = 22;
    }
    else if ((month == 2) && isLeapYear && (day > 29)) {
        err = 23;
    }
    else if ((month == 2) && !isLeapYear && (day > 28)) {
        err = 24;
    }
    /* Validation of other months */
    else if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
        err = 25;
    }
    else if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
        err = 26;
    }
    /* if 00 ist entered, no error, deleting the entry */
    else if ((day == 0) && (month == 0) && (year == 00)) {
        err = 0; day = ""; month = ""; year = ""; seperator = "";
    }

    /* if no error, write the completed date to Input-Field (e.g. 13/12/2001) */
    if (err == 0) {
        DateField.value = day + seperator + month + seperator + year;
        return true;
    }
    /* Error-message if err != 0 */
    else {
        alert("You have not entered a valid date.\nPlease enter a date in the format dd/mm/yyyy before proceeding.");
        DateField.focus();
        return false;
    }
}

function CheckDateDif(field, type)
{
    var startValue = document.forms[0].datefrom.value
    var endValue = document.forms[0].dateto.value

    var SDate = new Date(startValue.substring(6,10), startValue.substring(3,5)-1,startValue.substring(0,2));// eg YYYY/MM/DD
    var EDate = new Date(endValue.substring(6,10), endValue.substring(3,5)-1,endValue.substring(0,2));// eg YYYY/MM/DD
    var differenceRtn = EDate.getTime() - SDate.getTime();
    var daysDifferenceRtn = Math.floor(differenceRtn/1000/60/60/24);
    if(parseFloat(differenceRtn) < 0)
    {
        alert('End Date Must be Equal or After Start Date.  Please amend the End Date field before proceeding.');
        field.focus();
    }
}

function dateDiff(dateOne, dateTwo)
{
    var difference = dateTwo.getTime() - dateOne.getTime();
    return parseFloat(difference);
}

function dateDiffDays(dateOne, dateTwo)
{
    var difference = dateDiff(dateOne, dateTwo);
    return Math.floor(difference / 1000 / 60 / 60 / 24);
}

function trim(inputString)
{
    if (typeof inputString != "string")
        return inputString;

    var retValue = inputString;
    var ch = retValue.substring(0, 1);
    while (ch == " ")
    {
        retValue = retValue.substring(1, retValue.length);
        ch = retValue.substring(0, 1);
    }
    ch = retValue.substring(retValue.length-1, retValue.length);
    while(ch == " ")
    {
        retValue = retValue.substring(0, retValue.length-1);
        ch = retValue.substring(retValue.length-1, retValue.length);
    }
    while (retValue.indexOf("  ") != -1)
    {
        retValue = retValue.substring(0, retValue.indexOf("  "))
            + retValue.substring(retValue.indexOf("  ")+1, retValue.length);
    }
    return retValue;
}

function toggleDisplayByIdPrefix(id_prefix)
{
    var num = 0;
    var found = true;
    var id;
    while(found)
    {
        id = id_prefix + num;
        if(document.getElementById(id) != null)
        {
            toggleDisplayById(id);
            found = true;
        }
        else
            found = false;
        num++;
    }
}

function hide(object)
{
    object.style.visibility = "hidden";
    object.style_display = object.style.display;
    object.style.display = "none";
}

function show(object)
{
    object.style.visibility = "visible";
    object.style.display = (object.style_display == null ? "" : object.style_display);
    object.style_display = null;
}

function toggleDisplayById(id)
{
    toggleDisplay(document.getElementById(id));
}

function toggleDisplay(object)
{
    if(object.style.visibility == "visible")
        hide(object);
    else
        show(object);
}

function toggleDisplayChildrenById(id)
{
    toggleDisplayChildren(document.getElementById(id));
}

function toggleDisplayChildren(object)
{
    var i = 0;
    while(object.childNodes[i] != null)
    {
        child = object.childNodes[i];
        toggleDisplay(child);
        i++;
    }
}

function hideChildrenById(id)
{
    hideChildren(document.getElementById(id));
}

function hideById(id)
{
    hide(document.getElementById(id));
}

function showById(id)
{
    show(document.getElementById(id));
}

function showChildren(object)
{
    showhideChildren(object, true);
}

function showChildrenById(id)
{
    showChildren(document.getElementById(id));
}

function hideChildren(object)
{
    showhideChildren(object, false);
}

function showhideChildren(object, showing)
{
    var i = 0;
    while(object.childNodes[i] != null)
    {
        child = object.childNodes[i];
        if(showing)
            show(child);
        else
            hide(child);
        i++;
    }
}

function showhideByIdPrefix(id_prefix, show)
{
    var num = 0;
    var found = true;
    var id;
    var object;
    while(found)
    {
        id = id_prefix + num;
        object = document.getElementById(id);
        if(object != null)
        {
            if(show)
                object.style.visibility = 'visible';
            else
                object.style.visibility = 'hidden';
            found = true;
        }
        else
            found = false;
        num++;
    }
}

function showByIdPrefix(id_prefix)
{
    showhideByIdPrefix(id_prefix, true);
}

function hideByIdPrefix(id_prefix)
{
    showhideByIdPrefix(id_prefix, false);
}

function enable(object)
{
    object.disabled = false;
    object.className = (object.class_name == null ? "" : object.class_name);
    object.class_name = null;
}

function disable(object)
{
    object.disabled = true;
    object.class_name = object.className;
    object.className = "disabled";
}

function disableById(id)
{
    disable(document.getElementById(id));
}

function enableById(id)
{
    enable(document.getElementById(id));
}

function swapImage(image)
{
    image.src = "pasc/images/arrow-" + (image.src.indexOf("open") > 0 ? "closed" : "open") + ".gif";
}

function setChildIds(object, new_id)
{
    var i = 0;
    while(object.childNodes[i] != null)
    {
        child = object.childNodes[i];
        child_class = child.className;
        if(child_class != null && child_class != "")
            child.id = new_id;
        i++;
    }
}

function setChildIdsById(id, new_id)
{
    setChildIds(document.getElementById(id), new_id);
}

function isValidCashAmount(amount) {

    //returns true if amount is a valid number with up to 2 decimal places

    //if amount is empty, return false
    if (trim(amount) == "") {
        return false;
    }

    //if amount is not numerical, return false.
    if (isNaN(amount)) {
        return false;
    }


    //if amount contains no decimal point, return true
    if (amount.indexOf(".") == -1)
    {
        return true;
    }


    //if there are more than two decimal places, return false
    if (amount.length - amount.indexOf(".") > 3)
    {
        return false;
    }

    //otherwise

    return true;
}

function formatCashAmount(field) {

    //pads a cash amount field put to two decimal places

    field.value = trim(field.value);

    //if amount contains no decimal points, pad with ".00"
    if (field.value.indexOf(".") == -1) {
        field.value += ".00";
    }

    //if there is no characters after decimal place, pad with "00"
    if (field.value.length - field.value.indexOf(".") == 1) {
        field.value += "00";
    }

    //if there is no characters after decimal place, pad with "0"
    if (field.value.length - field.value.indexOf(".") == 2) {
        field.value += "0";
    }

}

function validateAndFormatCashField(field, errorMessage) {

    //if field is a valid cash amount, then format it
    //otherwise display error message and put focus in field

    if (!isValidCashAmount(field.value)) {
        alert(errorMessage);
        field.focus();
        return false;
    }
    else {
        formatCashAmount(field);
    }

    return true;
}

function setObject(object)
{
    setFieldValue("object", object);
}

function setAction(action)
{
    setFieldValue("action", action);
}

function setTarget(target)
{
    setFieldValue("target", target);
}

function setMenuId(mn)
{
    setFieldValue("mn", mn);
}

function setOpId(op)
{
    setFieldValue("op", op);
}

function validateNonEmptyField(field, errorMessage) {

    //if specified field is empty, display error message and return false

    if (trim(field.value) == "") {
        alert(errorMessage);
        field.focus();
        return false;
    }

    return true;
}

function isIntegerById(id)
{
    return isInteger(document.getElementById(id));
}

function isInteger(value) {

    //returns true if amount is a valid integer

    //if amount is empty, return false
    if (trim(value) == "") {
        return false;
    }

    //if amount is not numerical, return false.
    if (isNaN(value)) {
        return false;
    }

    var floatValue = parseFloat(value);

    return (Math.round(floatValue) == floatValue);

}

function validateAndFormatIntegerField(field, errorMessage) {

    //if field is a valid integer value, then format it
    //otherwise display error message and put focus in field

    if (!isInteger(field.value)) {
        alert(errorMessage);
        field.focus();
        return false;
    }
    else {
        field.value = Math.round(parseFloat(trim(field.value)));
    }

    return true;
}

function isValidEmail(emailAddress){

    //valid format is xxx@xxx.xxx where xxx means one or more of any character
    //the @ and the . are compulsary

    var format = /.+@.+(\..+)+$/;
    if(format.test(emailAddress)) return true;
    return false;
}

//Function to load date data.
function jsDatePicker( szField, szDate, szAction){
    var form = document.forms[0];
    var field = form.elements[szField];
    if(szAction == "1"){
        field.value=szDate;
    }
    return field.value;

}

function timetablesAction() {
	document.location="http://www.citylink.co.uk/timetables.htm";
}

function ticketTypeAction() {
	alert("ticketTypeAction");
}

function howToBuyAction() {
	document.location="http://www.citylink.co.uk/howtobuy.htm";
}
