
//-Begin Section -metadata.js-\\
// MetaData javascript functions

function ChangeCheckList(hidCheckBox, arrayName, e, fn) {
    //debugger;


    var hidControl = document.getElementById(hidCheckBox);
    var srcControl;
    var strID;
    var astrID;
    var myArray = eval(arrayName);
    var intIndex = 0;
    var astrValues;
    var intValuesLength;


    if (!e) {
        e = window.event;
    }

    srcControl = e.srcElement ? e.srcElement : e.target;

    //Find the index of this control in the checklist, it's the last bit of the control id
    strID = srcControl.id;
    astrID = strID.split('_');
    strID = astrID[astrID.length - 1];
    intIndex = parseInt(strID)
    //Get the value out of the javascript array
    var strValue = myArray[intIndex];

    //remove the value first so that there are no duplicates
    astrValues = hidControl.value.split(',');
    astrValues = ChangeCheckListArray(astrValues, strValue, srcControl.checked);
    hidControl.value = astrValues.toString();

    if ((typeof (fn) != 'undefined') && (typeof (fn) == 'string') && (fn != '')) {
        eval(fn);
    }

};

function ChangeCheckListArray(astrValues, value, add) {
    var astrNewValues = [];
    var intCount = astrValues.length;
    var blnFound = false;
    value = value.toLowerCase();
    for (intIndex = 0; intIndex < intCount; intIndex++) {
        if (astrValues[intIndex].toLowerCase() == value) {
            blnFound = true;
            if (add == true) {
                astrNewValues.push(astrValues[intIndex]);
            }
        }
        else {
            astrNewValues.push(astrValues[intIndex]);
        }
    }
    if ((add == true) && (blnFound == false)) {
        astrNewValues.push(value);
    }

    return astrNewValues;
};

function TreeView_ChangeCheckList(hidCheckBox, arrayName, e, treeNodeId) {
    var treeNode = document.getElementById(treeNodeId);
    var children = null;
    var childCount = 0;
    var childIndex = 0;
    var chkBox = null;
    var hidControl = document.getElementById(hidCheckBox);
    var myArray = eval(arrayName);
    var strID;
    var astrID;
    var intIndex;

    if (treeNode != null) {

        chkBox = treeNode.getElementsByTagName('input');

        if (chkBox[0].checked == true) {

            children = ob_getChildrenList(treeNode);
            childCount = children.length;

            for (childIndex = 0; childIndex < childCount; childIndex++) {
                chkBox = children[childIndex].getElementsByTagName('input');
                if (chkBox[0].checked == false) {
                    chkBox[0].checked = true;


                    //Find the index of this control in the checklist, it's the last bit of the control id
                    strID = chkBox[0].id;
                    astrID = strID.split('_');
                    strID = astrID[astrID.length - 1];
                    intIndex = parseInt(strID)
                    //Get the value out of the javascript array
                    var strValue = myArray[intIndex];


                    //remove the value first so that there are no duplicates
                    astrValues = hidControl.value.split(',');
                    astrValues = ChangeCheckListArray(astrValues, strValue, chkBox[0].checked);
                    hidControl.value = astrValues.toString();

                }
                TreeView_ChangeCheckList(hidCheckBox, arrayName, e, children[childIndex].id);
            }
        }
        else {
            children = ob_getChildrenList(treeNode);
            childCount = children.length;

            for (childIndex = 0; childIndex < childCount; childIndex++) {
                chkBox = children[childIndex].getElementsByTagName('input');
                if (chkBox[0].checked == true) {
                    chkBox[0].checked = false;


                    //Find the index of this control in the checklist, it's the last bit of the control id
                    strID = chkBox[0].id;
                    astrID = strID.split('_');
                    strID = astrID[astrID.length - 1];
                    intIndex = parseInt(strID)
                    //Get the value out of the javascript array
                    var strValue = myArray[intIndex];


                    //remove the value first so that there are no duplicates
                    astrValues = hidControl.value.split(',');
                    astrValues = ChangeCheckListArray(astrValues, strValue, chkBox[0].checked);
                    hidControl.value = astrValues.toString();

                }
                TreeView_ChangeCheckList(hidCheckBox, arrayName, e, children[childIndex].id);
            }
        }

    }
};
//-End Section -metadata.js-\\


//-Begin Section -validation.js-\\
// 
var bValidateOverride = false;
var bValidateItemOverride = false;


function CheckPage(validationGroup, useStatusArea) {
    if (typeof (Validate) != 'undefined') {
        return Validate.Check(validationGroup, useStatusArea);
    }
    else {
        return true;
    }
};

var Validator = Class.create();
Validator.prototype = {
    items: [],

    initialize: function()
    { },

    Add: function(control, conditions, messages, runOnCheckAll, runOnBlur, runOnClick, addToBlur, addToMouseOut) {
        if (control != null) {
            this.items.push(new ValidatorItem(control, conditions, messages, runOnCheckAll, runOnBlur, runOnClick, false));

            if (addToMouseOut == true) {
                control.onmouseout = function() { Validate.CheckThis(this, event) };
            }
            if (addToBlur == true) {
                control.onblur = function() { Validate.CheckThis(this, event) };
            }
        }

    },

    AddById: function(controlId, conditions, messages, runOnCheckAll, runOnBlur, runOnClick, addToBlur, addToMouseOut) {
        if (controlId != null) {
            this.items.push(new ValidatorItem(controlId, conditions, messages, runOnCheckAll, runOnBlur, runOnClick, true));
        }

    },


    Check: function(validationGroup, useStatusArea) {
        if ((typeof (validationGroup) == 'undefined') || (validationGroup == null)) {
            validationGroup = '';
        }
        return this.CheckThis(null, null, validationGroup, useStatusArea);
    },

    CheckThis: function(checkcontrol, e, validationGroup, useStatusArea) {
        var focusId;
        var eventType = '';
        var itemCount;

        if ((e) && (e != null)) {
            eventType = e.type;
        }
        //Clear the alternativeFocusId
        alternativeFocusId = null;
        if (bValidateOverride) {
            return true;
        }
        else if ((bValidateItemOverride) && (checkcontrol != null)) {
            return false;
        }
        else if ((messageArea) && (messageArea.messageRaised)) {
            return false;
        }
        if ((typeof (useStatusArea) == 'undefined') || (useStatusArea == null)) {
            useStatusArea = false;
        }

        itemCount = this.items.length;

        for (var iLoop = 0; iLoop < itemCount; iLoop++) {
            if (this.items[iLoop].control != null) {
                if ((checkcontrol == null) || (this.items[iLoop].control.id == checkcontrol.id)) {
                    for (var iCondition = 0; iCondition < this.items[iLoop].rules.length; iCondition++) {
                        //Very important. 'that' is the name used to identify the object being tested
                        //'that' must be passed in as part of the test so we can use isNAN(that.value) and such like.
                        var that = this.items[iLoop].control;
                        if (this.items[iLoop].isId) {
                            that = document.getElementById(that);
                        }

                        if ((that != null) && (this.items[iLoop].rules[iCondition].condition.validationGroup == validationGroup) && (this.isDisabled(that) == false) && (this.isReadOnly(that) == false)) {
                            //Check to see if this is an onblur event.
                            //e.g. do not eval an on blur event on checking all controls.
                            if ((checkcontrol != null) || (this.items[iLoop].rules[iCondition].runOnCheckAll == 'true')) {
                                if (!eval(this.items[iLoop].rules[iCondition].condition.rule)) {
                                    //Only display a message if one has been defined.
                                    if (typeof (this.items[iLoop].rules[iCondition].message) != 'undefined') {
                                        if (alternativeFocusId != null) {
                                            focusId = alternativeFocusId;
                                        }
                                        else {
                                            focusId = this.items[iLoop].control.id;
                                        }
                                        if (useStatusArea == true) {
                                            StatusArea.clear();
                                            StatusArea.add('Fatal', this.items[iLoop].rules[iCondition].message);
                                        }
                                        else {
                                            var msgShown = raiseMessage('validation', this.items[iLoop].rules[iCondition].message, focusId);
                                        }
                                        return false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return true;
    },

    isDisabled: function(that) {
        //Returns true if the control is disabled.
        //else returns false (e.g. if control is not disabled or control does not have a disabled property).
        if (typeof (that.disabled) == 'boolean') {
            return that.disabled;
        }
        else {
            return false;
        }
    },

    isReadOnly: function(that) {
        //Returns true if the control is readOnly.
        //else returns false (e.g. if control is not readOnly or control does not have a readOnly property).
        if (typeof (that.readOnly) == 'boolean') {
            return that.readOnly;
        }
        else {
            return false;
        }
    }
};

var ValidatorItem = Class.create();
ValidatorItem.prototype = {
    control: null,
    rules: null,
    isId: false,
    initialize: function(control, conditions, messages, runOnCheckAll, runOnBlur, runOnClick, isId) {
        this.control = control;
        this.rules = [];
        this.isId = isId;

        for (var ruleIndex = 0; ruleIndex < conditions.length; ruleIndex++) {
            this.rules.push(new ValidatorRule(conditions[ruleIndex], messages[ruleIndex], runOnCheckAll[ruleIndex], runOnBlur[ruleIndex], runOnClick[ruleIndex]));
        }
    }
};
var ValidatorRule = Class.create();
ValidatorRule.prototype = {
    condition: null,
    message: null,
    runOnCheckAll: false,
    runOnBlur: false,
    runOnClick: false,

    initialize: function(condition, message, runOnCheckAll, runOnBlur, runOnClick) {
        this.condition = condition;
        this.message = message;
        this.runOnCheckAll = runOnCheckAll;
        this.runOnBlur = runOnBlur;
        this.runOnClick = runOnClick;
    }
};


/********************************************************************************
Functions
*********************************************************************************/

function isMatch(strValue, strExpression) {
    var rgMatch = new RegExp(strExpression);
    return strValue.match(rgMatch)
}

function upperCase(that) {
    that.value = that.value.toUpperCase();
    return true;
}

function lowerCase(that) {
    that.value = that.value.toLowerCase();
    return true;
}

function normalCaseFirst(that) {
    that.value = toNormalCase(that.value, ' ', false);
    return true;
}

function normalCaseAll(that) {
    that.value = toNormalCase(that.value, ' ', true);
    return true;
}

function compareDate(strdate_1, strdate_2, strmode) {
    //debugger;
    var ret_val = false;
    if (
        typeof (strdate_1) != 'undefined' &&
        typeof (strdate_2) != 'undefined' &&
        strdate_1 != '' &&
        strdate_2 != ''
    ) {
        //This should really check for valid dates either before or after we have created the date objects.
        var new_date_1 = toDate(strdate_1);
        var new_date_2 = toDate(strdate_2);
        switch (strmode) {
            case "greater":
                ret_val = new_date_1 > new_date_2;
                break;
            case "less":
                ret_val = new_date_1 < new_date_2;
                break;
            case "equal":
                ret_val = new_date_1 == new_date_2;
                break;
            case "equgreater":
                ret_val = new_date_1 >= new_date_2;
                break;
            case "equless":
                ret_val = new_date_1 <= new_date_2;
                break;
            default:
                //No mode so return false.
                ret_val = false;
                break;
        }
    }
    else {
        return true;
    }
    return ret_val;
}

function toNormalCase(this_string, word_seperator, all_words) {
    /*
    *toNormalCase sets the first letter of one or more words to capital
    *
    * this_string    - string ('')     - The string to be capitalised
    * word_seperator - string (' ')    - Character between words 
    * all_words      - boolean (false) - False capitalises first word only, true capitalises all words
    */
    //Init vars
    var first_letter = new String();
    var other_letters = new String();
    var temp_string = new String();
    //check parameters
    if (word_seperator == null) {
        word_seperator = ' ';
    }
    if (all_words != true) {
        all_words = false
    }
    this_string = this_string.toLowerCase();
    //All words or just the first?
    if (all_words) {
        //Capitalise all words
        var temp_words = new Array();
        temp_words = this_string.split(word_seperator);
        var word_num = 0;
        //Iterate through words
        for (word_num = 0; word_num < temp_words.length; word_num++) {
            first_letter = temp_words[word_num].charAt(0);
            other_letters = temp_words[word_num].substring(1, temp_words[word_num].length);
            first_letter = first_letter.toUpperCase();
            if (temp_string == '') {
                temp_string += first_letter + other_letters
            }
            else {
                temp_string += word_seperator + first_letter + other_letters
            }
        }
    }
    else {
        //Capitalise first word only
        first_letter = this_string.charAt(0);
        other_letters = this_string.substring(1, this_string.length);
        first_letter = first_letter.toUpperCase();
        temp_string = first_letter + other_letters
    }
    return (temp_string);
}


function isValidDecimalPercent(that, min, max) {
    /*
    Returns a boolean based on whether the value passed in is a number and is between the min and max values.
    true - if all criteria were met
    false - if any of the criteria were not met. 
    */
    var return_value = true;
    if (isNaN(that)) {
        return_value = false;
    }
    else {
        if (that > max || that < min) {
            return_value = false;
        }
        if (that.indexOf('.') > -1) {
            var this_value = that.toString();
            var value_array = new Array();
            value_array = this_value.split('.');
            //debug_print(value_array.length);
            if (value_array.length > 0) {
                var decimal_part = value_array[1].toString();
                //debug_print(decimal_part);
                if (decimal_part.length > 2) {
                    return_value = false;
                }
            }
        }
    }
    return return_value;
};


function isNumeric(expression) {
    var validChars = "0123456789.";
    var validSignChars = "-+";
    var charValue;
    var decimalPointCount = 0;
    if ((expression != null) && (expression != 'undefined')) {
        for (var charIndex = 0; charIndex < expression.length; charIndex++) {
            charValue = expression.charAt(charIndex);
            if (validChars.indexOf(charValue) == -1) {
                //This may have a sign operator
                if (!((charIndex == 0) && (validSignChars.indexOf(charValue) != -1))) {
                    return false;
                }
            }
            if (charValue == '.') {
                decimalPointCount++;
            }
        }
        if (decimalPointCount < 2) {
            return true;
        }
        return true;
    }
    else {
        return false;
    }
};

//Nick
function isGenericPhoneNo(strPhone) {
    // Check for correct phone number
    rePhoneNumber = new RegExp(/^\+?\d[-\s\d]*\d$/);

    if (strPhone == '') {
        return true;
    }

    if (!rePhoneNumber.test(strPhone)) {
        return false;
    }

    return true;

};

//orv
function isEmail(strEmail) {
    // Check for valid email address
    var reExp;

    if (strEmail == '') {
        return true;
    }

    reExp = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
    return reExp.test(strEmail);
};

function isDate(strDate) {
    //return !isNaN(new Date(p_Expression));		// <<--- this needs checking
    /* 
    checked, this does not work. or at least not in my tests
    */
    /*try this
    known issues:
    haven't tested all date formats supported
    */
    if (bValidateOverride) {
        //debug_print('Validation override in place. Skipping validation');
        return true;
    }
    /*
    This could be extended to be from a passed in format parameter instead of 'hardcoded' to dd/mm/yyy.
    */
    // order of d/m/y - 0/1/2
    var iDay = 0;
    var iMonth = 1;
    var iYear = 2;
    // splitChar - Default to nothing, this would make it fail if it is left, however if no split char is matched later the function returns false anyway..
    var splitChar = '';
    // declaration of our regexp for use later.
    var validformat;
    /*These regexp's force a format of 
    [0][1->9] or 1[0->9] or 2[0->9] 3[0-1] for the day
    [0][1-9] or 1[0->2] for the month
    1[000->999] or 2[000->999] for the year
    This has been changed now to make the leading 0's optional in all relevant places.
    Needs to be heavily tested with many dates and formats.
    Supported should be
    01/01/2006
    1/1/2006
    01.01.2006
    1.1.2006
    01-01-2006
    1-1-2006
    01\01\2006
    1\1\2006
    */
    //find SplitChar and set format regexp.
    if (strDate.indexOf('/') >= 0) {
        validformat = new RegExp(/(0?[1-9]|[12][0-9]|3[01])(\/)(0?[1-9]|1[0-2])(\/)[129][0-9]{3}/);
        splitChar = '/';
    }
    else if (strDate.indexOf('.') >= 0) {
        validformat = new RegExp(/(0?[1-9]|[12][0-9]|3[01])(\.)(0?[1-9]|1[0-2])(\.)[129][0-9]{3}/);
        splitChar = '.';
    }
    else if (strDate.indexOf('-') >= 0) {
        validformat = new RegExp(/(0?[1-9]|[12][0-9]|3[01])(\-)(0?[1-9]|1[0-2])(\-)[129][0-9]{3}/);
        splitChar = '-';
    }
    else if (strDate.indexOf('\\') >= 0) {
        validformat = new RegExp(/(0?[1-9]|[12][0-9]|3[01])(\\)(0?[1-9]|1[0-2])(\\)[129][0-9]{3}/);
        splitChar = '\\';
    }
    else {
        //Failover condition. None of the above matched so return failure.
        return false;
    }
    //debugger;
    if (!strDate.match(validformat)) {
        //Regexp test, if it fails then return failure.
        return false;
    }
    else {
        //Else process the date further to determine validity as real date.
        //This should be checking for things like feb 29th feb 30th feb 31st.
        var dayfield = strDate.split(splitChar)[iDay]
        var monthfield = strDate.split(splitChar)[iMonth]
        var yearfield = strDate.split(splitChar)[iYear]
        var dayobj = new Date(yearfield, monthfield - 1, dayfield)
        if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
            return false;
        }
        else {
            return true;
        }
    }
    return true;
}

function toDate(expression) {
    /*
    returns a valid date object.
    expected date format is that of the calendar control.
    e.g. d/m/yyyy
    NOTE: if the date is not valid then this function will return 
    the current date.
    If you need to check date is valid please use isDateValid()
    before calling.
    */

    if ((typeof (expression) != 'undefined') && (typeof (expression.setYear) != 'undefined')) {
        //expression is already a date.
        return expression;
    }
    else if ((typeof (expression) == 'string') && (expression.indexOf('new Date(') > 0)) {
        return eval(expression);
    }
    else if (typeof (expression) == 'number') {
        return new Date(expression);
    }


    var sStartDate = expression.split('/');
    var day = 0;
    var month = 0;
    var year = 0;
    if (sStartDate.length > 0) {
        day = parseInt(sStartDate[0]);
    }
    if (sStartDate.length > 1) {
        month = parseInt(sStartDate[1]);
    }
    if (sStartDate.length > 2) {
        year = parseInt(sStartDate[2]);
    }
    if (day == 0) {
        day = new Date().getDate();
    }
    if (month == 0) {
        month = new Date().getMonth();
    }
    if (year == 0) {
        year = new Date().getYear();
    }
    return new Date(year, month, day);
}

// Numeric
// Ahsan 24/10/2006
function numericComparisons(expression, compareValue, whichComparison) {
    //debugger;
    var value = null;
    var blnComparison = false;

    if (expression == '') {
        return true;
    }

    if ((expression != null) && (expression != 'undefined')) {
        switch (whichComparison.toLowerCase()) {
            case 'numericgreaterthanorequalto':
                value = getNumeric(expression, '-.+', true);
                if (value >= compareValue) {
                    blnComparison = true;
                }
                break;

            case 'numericlessthanorequalto':
                value = getNumeric(expression, '-.+', true);
                if (value <= compareValue) {
                    blnComparison = true;
                }
                break;

            case 'numericlessthan':
                value = getNumeric(expression, '-.+', true);
                if (value < compareValue) {
                    blnComparison = true;
                }
                break;

            case 'numericgreaterthan':
                value = getNumeric(expression, '-.+', true);
                if (value > compareValue) {
                    blnComparison = true;
                }
                break;

            case 'numericnotlongerthan':
                value = getNumeric(expression, '', true);
                if (value.length <= compareValue) {
                    blnComparison = true;
                }
                break;

            case 'numericnotshorterthan':
                value = getNumeric(expression, '', true);
                if (value.length >= compareValue) {
                    blnComparison = true;
                }
                break;

            case 'numericlengthequalto':
                value = getNumeric(expression, '', true);
                if (value.length == compareValue) {
                    blnComparison = true;
                }
                break;

            case 'numericnotblank':
                value = getNumeric(expression, '', true);
                if (value.length > 0) {
                    blnComparison = true;
                }
                break;

            case 'numericbutnotdecimal':

                value = getNumeric(expression, '+.-', true);
                var intValue = parseInt(value);

                if (value == intValue) {
                    blnComparison = true;
                }
                break;

            default:
                blnComparison = false;
        }
    }
    else {
        blnComparison = false;
    }

    return blnComparison;
};

function getNumericValue(that, allowTheseExtras, blnTreatAsANumber) {
    that.value = getNumeric(that.value, allowTheseExtras, blnTreatAsANumber);
    return true;
};

/*
Function: 
getNumeric
Parameters: 
expression: input string.
allowTheseExtras: chars to be allowed other than numbers.
blnTreatAsANumber: will treat expression as a number. when
true, allowTheseExtras should only include +, period or a - sign.
Returns: 
Numeric value of expression (input string)
Example:
getNumeric('£  -1.01d', '.', true) will return -1.01
getNumeric('£  -1.01.', '.', true) will return false
Author: 
Ahsan 23/10/2006
*/
function getNumeric(expression, allowTheseExtras, blnTreatAsANumber) {
    //debugger;
    var blnDecimal = false;
    var blnPositiveNegative = false;
    var strExpression = '';
    var chrAtIndex;
    var numList = '0123456789';
    var iCharIndex = 0;

    if ((expression != null) && (expression != 'undefined')) {
        for (iCharIndex = 0; iCharIndex < expression.length; iCharIndex++) {
            chrAtIndex = expression.charAt(iCharIndex);

            if ((!(numList.indexOf(chrAtIndex) == -1)) || (!(allowTheseExtras.indexOf(chrAtIndex) == -1))) {
                if (blnTreatAsANumber) {
                    if ((chrAtIndex == '.') && (blnDecimal)) {
                        // allow only one decimal occurance.
                        return false;
                    }
                    else if (chrAtIndex == '.') {
                        // first occurrence of decimal
                        blnDecimal = true;
                    }
                    else if (((blnPositiveNegative) && (chrAtIndex == '-')) || ((chrAtIndex == '+') && (blnPositiveNegative))) {
                        // allow only one occurrence of + or - sign
                        return false;
                    }
                    else if ((chrAtIndex == '-') || (chrAtIndex == '+')) {
                        // first occurance of - or + sign
                        blnPositiveNegative = true;
                    }
                }

                // concat to return string
                strExpression = strExpression.concat(chrAtIndex);

            }
        }

        return strExpression;
    }
    else {
        return false;
    }
};
 

//-End Section -validation.js-\\


//-Begin Section -Gmap.js-\\

// this variable will collect the html which will eventually be placed in the sidebar
var sidebar_html = "";
// this is the handle to the map
var map = "";
// arrays to hold copies of the markers and html used by the sidebar
// because the function closure trick doesnt work there
var gmarkers = [];
var htmls = [];
var intCount = 0;
// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];
var counter = 0;

var prefix = '';

var intZoom = 9;

var sidebar_mode = 0;
var sidebar_title = '';
var map_title = '';

var center_lat = '';
var center_lon = '';

var enable_overview = 1;

var blnDirections = 'true';

function GetXmlNodeText(node)
{ 
    if(node && node.text)
    { 
        return node.text; 
    }
    else if(node && node.textContent)
    { 
        return node.textContent; 
    } 
    else
    {
		return '';
    }
}

if (GBrowserIsCompatible()) {
  // A function to create the marker and set up the event window
  function createMarker(point,name,html,iconcolour) {
    counter++;
    
    var icon = new GIcon();
    icon.image = mstrAppPath + "_themes/googlemap/images/mm_20_" + iconcolour + ".png"; //
    icon.iconSize = new GSize(12, 20);

    icon.shadow = mstrAppPath + "_themes/googlemap/images/mm_20_shadow.png";
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);     
    
    
    var marker = new GMarker(point, icon);
    var finalhtml;
    
    if(blnDirections == 'true') {
        // The info window version with the "to here" form open
        to_htmls[intCount] = html + '<br><br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + intCount + ')" class="popuplnk">From here</a>' +
           '<br><br>Start address/postcode:<br><form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" size="30" maxlength="40" name="saddr" id="saddr" value="" /><br>' +
           '<input value="Get Directions" type="submit">' +
           '<input type="hidden" name="daddr" value="' +
           point.y + ',' + point.x + "(" + prefix + ' - ' + name + ")" + '"/>';
        // The info window version with the "to here" form open
        from_htmls[intCount] = html + '<br><br>Directions: <a href="javascript:tohere(' + intCount + ')" class="popuplnk">To here</a> - <b>From here</b>' +
           '<br><br>End address/postcode:<br><form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" size="30" maxlength="40" name="daddr" id="daddr" value="" /><br>' +
           '<input value="Get Directions" type="submit">' +
           '<input type="hidden" name="saddr" value="' +
           point.y + ',' + point.x + "(" + prefix + ' - ' + name + ")" + '"/>';
        // The inactive version of the direction info
        finalhtml = html + '<br><br>Directions: <a href="javascript:tohere('+ intCount +')" class="popuplnk">To here</a> - <a href="javascript:fromhere('+ intCount +')" class="popuplnk">From here</a>';
    }
    else {
        if(name!='') {
            finalhtml = '<strong>'+name + '</strong><br>' + html;
        }
        else {
            finalhtml = html;
        }
    }
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml('<div class="popup">'+finalhtml+'</div>');
    });
    /*
    MOUSEOVER INSTEAD
    GEvent.addListener(marker, "mouseover", function() {
      marker.openInfoWindowHtml('<div class="popup">'+finalhtml+'</div>');
    });
    */
    // save the info we need to use later for the sidebar
    gmarkers[intCount] = marker;
    htmls[intCount] = finalhtml;
    // add a line to the sidebar html
    if(sidebar_mode == 0) {
        sidebar_html += '<div id="side'+counter+'"><a href="javascript:myclick(' + intCount + ')" class="Office">' + name + '</a><br /></div>'; //' + html + '</div>';
    }
    else if(sidebar_mode == 1) {
        sidebar_html += '<div id="side'+counter+'"><a href="javascript:myclick(' + intCount + ')" class="Office">' + name + '</a><br />' + html + '</div>';
    }
    intCount++;
    return marker;
  }
  

  // This function picks up the click and opens the corresponding info window
  function myclick(i) {
    document.getElementById("mapcont").focus();    
    gmarkers[i].openInfoWindowHtml('<div class="popup">'+htmls[i]+'</div>');
  }

  // functions that open the directions forms
  function tohere(i) {
    gmarkers[i].openInfoWindowHtml('<div class="popup">'+ to_htmls[i]+'</div>');

  }
  function fromhere(i) {
    gmarkers[i].openInfoWindowHtml('<div class="popup">'+ from_htmls[i] +'</div>');
  }

function firstClick()
{
    myclick(0);   
}

	// Download the data in data.xml and load it on the map. The format we
	// expect is:
	// <markers>
	//   <marker lat="37.441" lng="-122.141" title="blah" desc="comp name1"/>
	//   <marker lat="37.322" lng="-121.213" title="blah" desc="comp name2"/>
	// </markers>
	function init() {
        var request = GXmlHttp.create();
        request.open("GET", xmlFile, true);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {





                var xmlDoc = request.responseXML;
                
                var mode_check = xmlDoc.getElementsByTagName("metadata");
                

                if(mode_check.length==1) {
                    //meta data xml
                    
                    //create the map and add a couple of toolbars
                    map = new GMap2(document.getElementById("mapcont"));
                    map.addControl(new GLargeMapControl()); //pan & zoom
                    //map.addControl(new GMapTypeControl());  //map type: map, satellite, hybrid
                    //map.addControl(new GOverviewMapControl());                   
                    
                    blnDirections = false;
                    intZoom = 6;
                    
   
                    var markers = xmlDoc.getElementsByTagName("item");
                    for (var i = 0; i < markers.length; i++) {
                    
                        var gpsLon = parseFloat(GetXmlNodeText(markers[i].getElementsByTagName("gpslongitude")[0]));
                        var gpsLat = parseFloat(GetXmlNodeText(markers[i].getElementsByTagName("gpslatitude")[0]));
                        if(i==0) {
                            //center near blackpool
                            map.setCenter(new GLatLng(parseFloat('54.6021'), parseFloat('-4.3636')), intZoom, null);
                        }
                        try {
                            var iconColour = GetXmlNodeText(markers[i].getElementsByTagName("mapiconcolour")[0]);
                        }
                        catch(e) {
                            var iconColour = 'red';
                        }
                        
                        if(!isNaN(gpsLon) && !isNaN(gpsLat)) {
                            var point = new GPoint(gpsLon,gpsLat);
                            var title = GetXmlNodeText(markers[i].getElementsByTagName("title")[0]);
                            var desc = GetXmlNodeText(markers[i].getElementsByTagName("description")[0]);
                            if(typeof(desc)=='undefined') {
                                desc = '';
                            }
                            var img = GetXmlNodeText(markers[i].getElementsByTagName("image")[0]);
                            var link = GetXmlNodeText(markers[i].getElementsByTagName("link")[0]);
                            var docpdfNode = markers[i].getElementsByTagName("pdfdocument")[0];
                            var docpdf = '';
                            if (docpdfNode != null)
                            {
								docpdf = GetXmlNodeText(docpdfNode);
							}
							
                            desc = '<table class="datatbl" cellspacing="0" cellpadding="0" border="0">'+
                                    '<tr>'+
                                    '<td valign="top"><strong>'+title+'</strong>'+
                                    desc;
                            
                            if(link!='') {
                                desc += '<br/><br/><a href="'+link+'">Read More</a>';
                            }
                            if(docpdf!='') {
                                desc += '<br/><a href="'+docpdf+'" target="_blank">Download PDF</a>';
                            }                        
                            
                            desc += '</td>';
                            
                            if(img!='')
                            {

                                desc += '<td width="10" nowrap></td>'+
                                        '<td valign="top" width="90" nowrap><img src="'+img+'" align="top" title="'+title+'" /></td>';
                            }
                            desc += '</tr>'+
                                '</table>';
                  
                            var marker = createMarker(point,'',desc,iconColour);
                            map.addOverlay(marker);
                        }
                    }   
                         
         
                    
                }
                else {
                
                    //create the map and add a couple of toolbars
                    map = new GMap2(document.getElementById("mapcont"));
                    map.addControl(new GLargeMapControl()); //pan & zoom
                    map.addControl(new GMapTypeControl());  //map type: map, satellite, hybrid


                    var properties = xmlDoc.documentElement.getElementsByTagName("property");
                    for (var i = 0; i < properties.length; i++) {
                        if(properties[i].getAttribute("name") == 'company_name') {
                            prefix = GetXmlNodeText(properties[i]);   
                        }
                        else if (properties[i].getAttribute("name") == 'sidebar_mode') {
                            sidebar_mode = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'sidebar_title') {
                            sidebar_title = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'map_title') {
                            map_title = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'zoom') {
                            intZoom = parseInt(GetXmlNodeText(properties[i]));
                        }
                        else if (properties[i].getAttribute("name") == 'directions') {
                            blnDirections = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'center_lat') {
                            center_lat = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'center_lon') {
                            center_lon = GetXmlNodeText(properties[i]);
                        }
                        else if (properties[i].getAttribute("name") == 'enable_overview') {
                            enable_overview = GetXmlNodeText(properties[i]);
                        }
                         
                    }	

                    if(parseInt(enable_overview) == 1)
                    {
                        //map.addControl(new GOverviewMapControl());    
						window.setTimeout("overview = new GOverviewMapControl();map.addControl(overview)",500); 

                    }
                    
                    
                    if(map_title != '') {
                        
                        var objMap = document.getElementById("mapcont");
                        if(objMap) {
                            var objTitle = document.createElement('h1');
                            objTitle.innerText = map_title;
                            objTitle.className = 'MapTitle';
                            objMap.insertAdjacentElement('beforeBegin', objTitle);
                            
                        }
                    }                
                    	    
                    var markers = xmlDoc.documentElement.getElementsByTagName("marker");
                    for (var i = 0; i < markers.length; i++) {
                        if(i==0) {
                            //center near first point
                            if(center_lat=='')
                            {
                               map.setCenter(new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng"))), intZoom, null);
                            }
                            else
                            {
                                map.setCenter(new GLatLng(parseFloat(center_lat), parseFloat(center_lon)), intZoom, null);
                            }
                        }
                        
                        try {
                            var iconColour = markers[i].getAttribute("icon").toString()
                        }
                        catch(e) {
                            var iconColour = 'red';
                        }
                        var point = new GPoint(parseFloat(markers[i].getAttribute("lng")),parseFloat(markers[i].getAttribute("lat")));
                        var title = markers[i].getAttribute("title").toString();
                        var desc = markers[i].getAttribute("desc").toString();
                        var marker = createMarker(point,title,desc,iconColour);
                        map.addOverlay(marker);
                    }
                    if(i==1)
                    {
                        firstClick();
                        
                    }
                }

                // put the assembled sidebar_html contents into the sidebar div
                //sidebar_html = '<h1 class="elContentTitle">Contact Us</h1>' + sidebar_html;
                if(document.getElementById("sidebar")) {
                    if(sidebar_title!='') {
                        sidebar_title = '<h1 class="SideBarTitle"><span>'+sidebar_title+'</span>'+sidebar_title+'</h1>';
                    }
                    document.getElementById("sidebar").innerHTML = sidebar_title + sidebar_html;
                }
            }
        }
        request.send(null);
    }

    Event.observe(window, 'load', init, false);
    //DomLoaded.load(init);
}
else {
  alert('Sorry, the Google Maps API is not compatible with this browser');
}  
 
//-End Section -Gmap.js-\\

//-End File-\\
