
/***************************************************************
***************************************************************
include/js/ajax/yahoo/yahoo.js
***************************************************************
**************************************************************/

/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
Version: 0.11.4
*/

/**
* The YAHOO object is the single global object used by YUI Library.  It
* contains utility function for setting up namespaces, inheritance, and
* logging.  YAHOO.util, YAHOO.widget, and YAHOO.example are namespaces
* created automatically for and used by the library.
* @module YAHOO
*/

/**
* The YAHOO global namespace object
* @class YAHOO
* @static
*/
if (typeof YAHOO == "undefined") {
    YAHOO = {};
}

/**
* Returns the namespace specified and creates it if it doesn't exist
*
* YAHOO.namespace("property.package");
* YAHOO.namespace("YAHOO.property.package");
*
* Either of the above would create YAHOO.property, then
* YAHOO.property.package
*
* Be careful when naming packages. Reserved words may work in some browsers
* and not others. For instance, the following will fail in Safari:
*
* YAHOO.namespace("really.long.nested.namespace");
*
* This fails because "long" is a future reserved word in ECMAScript
* @method namespace
* @static
* @param  {String} ns The name of the namespace
* @return {Object}    A reference to the namespace object
*/
YAHOO.namespace = function(ns) {

    if (!ns || !ns.length) {
        return null;
    }

    var levels = ns.split(".");
    var nsobj = YAHOO;

    // YAHOO is implied, so it is ignored if it is included
    for (var i = (levels[0] == "YAHOO") ? 1 : 0; i < levels.length; ++i) {
        nsobj[levels[i]] = nsobj[levels[i]] || {};
        nsobj = nsobj[levels[i]];
    }

    return nsobj;
};

/**
* Uses YAHOO.widget.Logger to output a log message, if the widget is available.
*
* @method log
* @static
* @param  {string}  sMsg       The message to log.
* @param  {string}  sCategory  The log category for the message.  Default
*                              categories are "info", "warn", "error", time".
*                              Custom categories can be used as well. (opt)
* @param  {string}  sSource    The source of the the message (opt)
* @return {boolean}            True if the log operation was successful.
*/
YAHOO.log = function(sMsg, sCategory, sSource) {
    var l = YAHOO.widget.Logger;
    if (l && l.log) {
        return l.log(sMsg, sCategory, sSource);
    } else {
        return false;
    }
};

/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
*
* @method extend
* @static
* @param {function} subclass   the object to modify
* @param {function} superclass the object to inherit
*/
YAHOO.extend = function(subclass, superclass) {
    var f = function() { };
    f.prototype = superclass.prototype;
    subclass.prototype = new f();
    subclass.prototype.constructor = subclass;
    subclass.superclass = superclass.prototype;
    if (superclass.prototype.constructor == Object.prototype.constructor) {
        superclass.prototype.constructor = superclass;
    }
};

YAHOO.namespace("util");
YAHOO.namespace("widget");
YAHOO.namespace("example");


/***************************************************************
***************************************************************
include/js/ajax/connection/connection.js
***************************************************************
**************************************************************/

/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
Version: 0.11.3
*/

/**
* The Connection Manager provides a simplified interface to the XMLHttpRequest
* object.  It handles cross-browser instantiantion of XMLHttpRequest, negotiates the
* interactive states and server response, returning the results to a pre-defined
* callback you create.
* @ class
*/
YAHOO.util.Connect =
{
    /**
    * Array of MSFT ActiveX ids for XMLHttpRequest.
    * @private
    * @type array
    */
    _msxml_progid: [
		'MSXML2.XMLHTTP.3.0',
		'MSXML2.XMLHTTP',
		'Microsoft.XMLHTTP'
		],

    /**
    * Object literal of HTTP header(s)
    * @private
    * @type object
    */
    _http_header: {},

    /**
    * Determines if HTTP headers are set.
    * @private
    * @type boolean
    */
    _has_http_headers: false,

    /**
    * Determines if a default header of
    * Content-Type of 'application/x-www-form-urlencoded'
    * will be added to any client HTTP headers sent for POST
    * transactions.
    * @private
    * @type boolean
    */
    _use_default_post_header: true,

    /**
    * Determines if a default header of
    * Content-Type of 'application/x-www-form-urlencoded'
    * will be added to any client HTTP headers sent for POST
    * transactions.
    * @private
    * @type boolean
    */
    _default_post_header: 'application/x-www-form-urlencoded',

    /**
    * Property modified by setForm() to determine if the data
    * should be submitted as an HTML form.
    * @private
    * @type boolean
    */
    _isFormSubmit: false,

    /**
    * Property modified by setForm() to determine if a file(s)
    * upload is expected.
    * @private
    * @type boolean
    */
    _isFileUpload: false,

    /**
    * Property modified by setForm() to set a reference to the HTML
    * form node if the desired action is file upload.
    * @private
    * @type object
    */
    _formNode: null,

    /**
    * Property modified by setForm() to set the HTML form data
    * for each transaction.
    * @private
    * @type string
    */
    _sFormData: null,

    /**
    * Collection of polling references to the polling mechanism in handleReadyState.
    * @private
    * @type object
    */
    _poll: {},

    /**
    * Queue of timeout values for each transaction callback with a defined timeout value.
    * @private
    * @type object
    */
    _timeOut: {},

    /**
    * The polling frequency, in milliseconds, for HandleReadyState.
    * when attempting to determine a transaction's XHR readyState.
    * The default is 50 milliseconds.
    * @private
    * @type int
    */
    _polling_interval: 50,

    /**
    * A transaction counter that increments the transaction id for each transaction.
    * @private
    * @type int
    */
    _transaction_id: 0,

    /**
    * Member to add an ActiveX id to the existing xml_progid array.
    * In the event(unlikely) a new ActiveX id is introduced, it can be added
    * without internal code modifications.
    * @public
    * @param string id The ActiveX id to be added to initialize the XHR object.
    * @return void
    */
    setProgId: function(id) {
        this._msxml_progid.unshift(id);
    },

    /**
    * Member to enable or disable the default POST header.
    * @public
    * @param boolean b Set and use default header - true or false .
    * @return void
    */
    setDefaultPostHeader: function(b) {
        this._use_default_post_header = b;
    },

    /**
    * Member to modify the default polling interval.
    * @public
    * @param {int} i The polling interval in milliseconds.
    * @return void
    */
    setPollingInterval: function(i) {
        if (typeof i == 'number' && isFinite(i)) {
            this._polling_interval = i;
        }
    },

    /**
    * Instantiates a XMLHttpRequest object and returns an object with two properties:
    * the XMLHttpRequest instance and the transaction id.
    * @private
    * @param {int} transactionId Property containing the transaction id for this transaction.
    * @return connection object
    */
    createXhrObject: function(transactionId) {
        var obj, http;
        try {
            // Instantiates XMLHttpRequest in non-IE browsers and assigns to http.
            http = new XMLHttpRequest();
            //  Object literal with http and tId properties
            obj = { conn: http, tId: transactionId };
        }
        catch (e) {
            for (var i = 0; i < this._msxml_progid.length; ++i) {
                try {
                    // Instantiates XMLHttpRequest for IE and assign to http.
                    http = new ActiveXObject(this._msxml_progid[i]);
                    //  Object literal with http and tId properties
                    obj = { conn: http, tId: transactionId };
                    break;
                }
                catch (e) { }
            }
        }
        finally {
            return obj;
        }
    },

    /**
    * This method is called by asyncRequest to create a
    * valid connection object for the transaction.  It also passes a
    * transaction id and increments the transaction id counter.
    * @private
    * @return object
    */
    getConnectionObject: function() {
        var o;
        var tId = this._transaction_id;

        try {
            o = this.createXhrObject(tId);
            if (o) {
                this._transaction_id++;
            }
        }
        catch (e) { }
        finally {
            return o;
        }
    },

    /**
    * Method for initiating an asynchronous request via the XHR object.
    * @public
    * @param {string} method HTTP transaction method
    * @param {string} uri Fully qualified path of resource
    * @param callback User-defined callback function or object
    * @param {string} postData POST body
    * @return {object} Returns the connection object
    */
    asyncRequest: function(method, uri, callback, postData) {
        var o = this.getConnectionObject();

        if (!o) {
            return null;
        }
        else {
            if (this._isFormSubmit) {
                if (this._isFileUpload) {
                    this.uploadFile(o.tId, callback, uri);
                    this.releaseObject(o);
                    return;
                }

                //If the specified HTTP method is GET, setForm() will return an
                //encoded string that is concatenated to the uri to
                //create a querystring.
                if (method == 'GET') {
                    uri += "?" + this._sFormData;
                }
                else if (method == 'POST') {
                    //If POST data exists in addition to the HTML form data,
                    //it will be concatenated to the form data.
                    postData = (postData ? this._sFormData + "&" + postData : this._sFormData);
                }
                this._sFormData = '';
            }

            o.conn.open(method, uri, true);

            if (this._isFormSubmit || (postData && this._use_default_post_header)) {
                this.initHeader('Content-Type', this._default_post_header);
                if (this._isFormSubmit) {
                    this._isFormSubmit = false;
                }
            }

            if (this._has_http_headers) {
                this.setHeader(o);
            }

            this.handleReadyState(o, callback);
            o.conn.send(postData ? postData : null);

            return o;
        }
    },

    /**
    * This method serves as a timer that polls the XHR object's readyState
    * property during a transaction, instead of binding a callback to the
    * onreadystatechange event.  Upon readyState 4, handleTransactionResponse
    * will process the response, and the timer will be cleared.
    *
    * @private
    * @param {object} o The connection object
    * @param callback User-defined callback object
    * @return void
    */
    handleReadyState: function(o, callback) {

        var oConn = this;

        if (callback && callback.timeout) {
            this._timeOut[o.tId] = window.setTimeout(function() { oConn.abort(o, callback, true); }, callback.timeout);
        }

        this._poll[o.tId] = window.setInterval(
			function() {
			    if (o.conn && o.conn.readyState == 4) {
			        window.clearInterval(oConn._poll[o.tId]);
			        delete oConn._poll[o.tId];

			        if (callback && callback.timeout) {
			            delete oConn._timeOut[o.tId];
			        }

			        oConn.handleTransactionResponse(o, callback);
			    }
			}
		, this._polling_interval);
    },

    /**
    * This method attempts to interpret the server response and
    * determine whether the transaction was successful, or if an error or
    * exception was encountered.
    *
    * @private
    * @param {object} o The connection object
    * @param {object} callback - User-defined callback object
    * @param {boolean} determines if the transaction was aborted.
    * @return void
    */
    handleTransactionResponse: function(o, callback, isAbort) {
        // If no valid callback is provided, then do not process any callback handling.
        if (!callback) {
            this.releaseObject(o);
            return;
        }

        var httpStatus, responseObject;

        try {
            if (o.conn.status !== undefined && o.conn.status != 0) {
                httpStatus = o.conn.status;
            }
            else {
                httpStatus = 13030;
            }
        }
        catch (e) {
            // 13030 is the custom code to indicate the condition -- in Mozilla/FF --
            // when the o object's status and statusText properties are
            // unavailable, and a query attempt throws an exception.
            httpStatus = 13030;
        }

        if (httpStatus >= 200 && httpStatus < 300) {
            try {
                responseObject = this.createResponseObject(o, callback.argument);
                if (callback.success) {
                    if (!callback.scope) {
                        callback.success(responseObject);
                    }
                    else {
                        // If a scope property is defined, the callback will be fired from
                        // the context of the object.
                        callback.success.apply(callback.scope, [responseObject]);
                    }
                }
            }
            catch (e) { }
        }
        else {
            try {
                switch (httpStatus) {
                    // The following case labels are wininet.dll error codes that may be encountered. 
                    case 12002: // Server timeout
                    case 12029: // 12029 to 12031 correspond to dropped connections.
                    case 12030:
                    case 12031:
                    case 12152: // Connection closed by server.
                    case 13030: // See above comments for variable status.
                        responseObject = this.createExceptionObject(o.tId, callback.argument, (isAbort ? isAbort : false));
                        if (callback.failure) {
                            if (!callback.scope) {
                                callback.failure(responseObject);
                            }
                            else {
                                callback.failure.apply(callback.scope, [responseObject]);
                            }
                        }
                        break;
                    default:
                        responseObject = this.createResponseObject(o, callback.argument);
                        if (callback.failure) {
                            if (!callback.scope) {
                                callback.failure(responseObject);
                            }
                            else {
                                callback.failure.apply(callback.scope, [responseObject]);
                            }
                        }
                }
            }
            catch (e) { }
        }

        this.releaseObject(o);
        responseObject = null;
    },

    /**
    * This method evaluates the server response, creates and returns the results via
    * its properties.  Success and failure cases will differ in the response
    * object's property values.
    * @private
    * @param {object} o The connection object
    * @param {} callbackArg User-defined argument or arguments to be passed to the callback
    * @return object
    */
    createResponseObject: function(o, callbackArg) {
        var obj = {};
        var headerObj = {};

        try {
            var headerStr = o.conn.getAllResponseHeaders();
            var header = headerStr.split('\n');
            for (var i = 0; i < header.length; i++) {
                var delimitPos = header[i].indexOf(':');
                if (delimitPos != -1) {
                    headerObj[header[i].substring(0, delimitPos)] = header[i].substring(delimitPos + 2);
                }
            }
        }
        catch (e) { }

        obj.tId = o.tId;
        obj.status = o.conn.status;
        obj.statusText = o.conn.statusText;
        obj.getResponseHeader = headerObj;
        obj.getAllResponseHeaders = headerStr;
        obj.responseText = o.conn.responseText;
        obj.responseXML = o.conn.responseXML;

        if (typeof callbackArg !== undefined) {
            obj.argument = callbackArg;
        }

        return obj;
    },

    /**
    * If a transaction cannot be completed due to dropped or closed connections,
    * there may be not be enough information to build a full response object.
    * The failure callback will be fired and this specific condition can be identified
    * by a status property value of 0.
    *
    * If an abort was successful, the status property will report a value of -1.
    *
    * @private
    * @param {int} tId Transaction Id
    * @param callbackArg The user-defined arguments
    * @param isAbort Determines if the exception is an abort.
    * @return object
    */
    createExceptionObject: function(tId, callbackArg, isAbort) {
        var COMM_CODE = 0;
        var COMM_ERROR = 'communication failure';
        var ABORT_CODE = -1;
        var ABORT_ERROR = 'transaction aborted';

        var obj = {};

        obj.tId = tId;
        if (isAbort) {
            obj.status = ABORT_CODE;
            obj.statusText = ABORT_ERROR;
        }
        else {
            obj.status = COMM_CODE;
            obj.statusText = COMM_ERROR;
        }

        if (callbackArg) {
            obj.argument = callbackArg;
        }

        return obj;
    },

    /**
    * Public method that stores the custom HTTP headers for each transaction.
    * @public
    * @param {string} label The HTTP header label
    * @param {string} value The HTTP header value
    * @return void
    */
    initHeader: function(label, value) {
        if (this._http_header[label] === undefined) {
            this._http_header[label] = value;
        }
        else {
            // Concatenate multiple values, comma-delimited,
            // for the same header label,
            this._http_header[label] = value + "," + this._http_header[label];
        }

        this._has_http_headers = true;
    },

    /**
    * Accessor that sets the HTTP headers for each transaction.
    * @private
    * @param {object} o The connection object for the transaction.
    * @return void
    */
    setHeader: function(o) {
        for (var prop in this._http_header) {
            if (this._http_header.hasOwnProperty(prop)) {
                o.conn.setRequestHeader(prop, this._http_header[prop]);
            }
        }
        delete this._http_header;

        this._http_header = {};
        this._has_http_headers = false;
    },

    /**
    * This method assembles the form label and value pairs and
    * constructs an encoded string.
    * asyncRequest() will automatically initialize the
    * transaction with a HTTP header Content-Type of
    * application/x-www-form-urlencoded.
    * @public
    * @param {string || object} form id or name attribute, or form object.
    * @param {string} optional boolean to indicate SSL environment.
    * @param {string || boolean} optional qualified path of iframe resource for SSL in IE.
    * @return void
    */
    setForm: function(formId, isUpload, secureUri) {
        this._sFormData = '';
        if (typeof formId == 'string') {
            // Determine if the argument is a form id or a form name.
            // Note form name usage is deprecated by supported
            // here for legacy reasons.
            var oForm = (document.getElementById(formId) || document.forms[formId]);
        }
        else if (typeof formId == 'object') {
            // Treat argument as an HTML form object.
            var oForm = formId;
        }
        else {
            return;
        }

        // If the isUpload argument is true, setForm will call createFrame to initialize
        // an iframe as the form target.
        //
        // The argument secureURI is also required by IE in SSL environments
        // where the secureURI string is a fully qualified HTTP path, used to set the source
        // of the iframe, to a stub resource in the same domain.
        if (isUpload) {
            this.createFrame(secureUri ? secureUri : null);
            this._isFormSubmit = true;
            this._isFileUpload = true;
            this._formNode = oForm;

            return;
        }

        var oElement, oName, oValue, oDisabled;
        var hasSubmit = false;

        // Iterate over the form elements collection to construct the
        // label-value pairs.
        for (var i = 0; i < oForm.elements.length; i++) {
            oElement = oForm.elements[i];
            oDisabled = oForm.elements[i].disabled;
            oName = oForm.elements[i].name;
            oValue = oForm.elements[i].value;

            // Do not submit fields that are disabled or
            // do not have a name attribute value.
            if (!oDisabled && oName) {
                switch (oElement.type) {
                    case 'select-one':
                    case 'select-multiple':
                        for (var j = 0; j < oElement.options.length; j++) {
                            if (oElement.options[j].selected) {
                                if (window.ActiveXObject) {
                                    this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].attributes['value'].specified ? oElement.options[j].value : oElement.options[j].text) + '&';
                                }
                                else {
                                    this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].hasAttribute('value') ? oElement.options[j].value : oElement.options[j].text) + '&';
                                }

                            }
                        }
                        break;
                    case 'radio':
                    case 'checkbox':
                        if (oElement.checked) {
                            this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
                        }
                        break;
                    case 'file':
                        // stub case as XMLHttpRequest will only send the file path as a string.
                    case undefined:
                        // stub case for fieldset element which returns undefined.
                    case 'reset':
                        // stub case for input type reset button.
                    case 'button':
                        // stub case for input type button elements.
                        break;
                    case 'submit':
                        if (hasSubmit == false) {
                            this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
                            hasSubmit = true;
                        }
                        break;
                    default:
                        this._sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
                        break;
                }
            }
        }

        this._isFormSubmit = true;
        this._sFormData = this._sFormData.substr(0, this._sFormData.length - 1);
    },

    /**
    * Creates an iframe to be used for form file uploads.  It is remove from the
    * document upon completion of the upload transaction.
    *
    * @private
    * @param {string} optional qualified path of iframe resource for SSL in IE.
    * @return void
    */
    createFrame: function(secureUri) {

        // IE does not allow the setting of id and name attributes as object
        // properties via createElement().  A different iframe creation
        // pattern is required for IE.
        var frameId = 'yuiIO' + this._transaction_id;
        if (window.ActiveXObject) {
            var io = document.createElement('<IFRAME id="' + frameId + '" name="' + frameId + '">');

            // IE will throw a security exception in an SSL environment if the
            // iframe source isn't set.
            if (typeof secureUri == 'boolean') {
                io.src = 'javascript:false';
            }
            else {
                io.src = secureUri;
            }
        }
        else {
            var io = document.createElement('IFRAME');
            io.id = frameId;
            io.name = frameId;
        }

        io.style.position = 'absolute';
        io.style.top = '-1000px';
        io.style.left = '-1000px';

        document.body.appendChild(io);
    },

    /**
    * Uploads HTML form, including files/attachments,  targeting the
    * iframe created in createFrame.
    *
    * @private
    * @param {int} id The transaction id.
    * @param {object} callback - User-defined callback object.
    * @param {string} uri Fully qualified path of resource.
    * @return void
    */
    uploadFile: function(id, callback, uri) {

        var frameId = 'yuiIO' + id;
        var io = document.getElementById(frameId);

        // Initialize the HTML form properties in case they are
        // not defined in the HTML form.
        this._formNode.action = uri;
        this._formNode.enctype = 'multipart/form-data';
        this._formNode.method = 'POST';
        this._formNode.target = frameId;
        this._formNode.submit();

        // Reset form status properties.
        this._formNode = null;
        this._isFileUpload = false;
        this._isFormSubmit = false;

        // Create the upload callback handler that fires when the iframe
        // receives the load event.  Subsequently, the event handler is detached
        // and the iframe removed from the document.

        var uploadCallback = function() {
            var obj = {};

            obj.tId = id;
            obj.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
            obj.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
            obj.argument = callback.argument;

            if (callback.upload) {
                if (!callback.scope) {
                    callback.upload(obj);
                }
                else {
                    callback.upload.apply(callback.scope, [obj]);
                }
            }

            if (YAHOO.util.Event) {
                YAHOO.util.Event.removeListener(io, "load", uploadCallback);
            }
            else if (window.ActiveXObject) {
                io.detachEvent('onload', uploadCallback);
            }
            else {
                io.removeEventListener('load', uploadCallback, false);
            }
            setTimeout(function() { document.body.removeChild(io); }, 100);
        };


        // Bind the onload handler to the iframe to detect the file upload response.
        if (YAHOO.util.Event) {
            YAHOO.util.Event.addListener(io, "load", uploadCallback);
        }
        else if (window.ActiveXObject) {
            io.attachEvent('onload', uploadCallback);
        }
        else {
            io.addEventListener('load', uploadCallback, false);
        }
    },

    /**
    * Public method to terminate a transaction, if it has not reached readyState 4.
    * @public
    * @param {object} o The connection object returned by asyncRequest.
    * @param {object} callback  User-defined callback object.
    * @param {string} isTimeout boolean to indicate if abort was a timeout.
    * @return void
    */
    abort: function(o, callback, isTimeout) {
        if (this.isCallInProgress(o)) {
            o.conn.abort();
            window.clearInterval(this._poll[o.tId]);
            delete this._poll[o.tId];
            if (isTimeout) {
                delete this._timeOut[o.tId];
            }

            this.handleTransactionResponse(o, callback, true);

            return true;
        }
        else {
            return false;
        }
    },

    /**
    * Public method to check if the transaction is still being processed.
    * @public
    * @param {object} o The connection object returned by asyncRequest
    * @return boolean
    */
    isCallInProgress: function(o) {
        // if the XHR object assigned to the transaction has not been dereferenced,
        // then check its readyState status.  Otherwise, return false.
        if (o.conn) {
            return o.conn.readyState != 4 && o.conn.readyState != 0;
        }
        else {
            //The XHR object has been destroyed.
            return false;
        }
    },

    /**
    * Dereference the XHR instance and the connection object after the transaction is completed.
    * @private
    * @param {object} o The connection object
    * @return void
    */
    releaseObject: function(o) {
        //dereference the XHR instance.
        o.conn = null;
        //dereference the connection object.
        o = null;
    }
};

/***************************************************************
***************************************************************
include/js/ajax/event/event.js
***************************************************************
**************************************************************/

/*
Copyright (c) 2006, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
Version: 0.11.4
*/

/**
* The CustomEvent class lets you define events for your application
* that can be subscribed to by one or more independent component.
*
* @param {String}  type The type of event, which is passed to the callback
*                  when the event fires
* @param {Object}  oScope The context the event will fire from.  "this" will
*                  refer to this object in the callback.  Default value:
*                  the window object.  The listener can override this.
* @param {boolean} silent pass true to prevent the event from writing to
*                  the log system
* @namespace YAHOO.util
* @class CustomEvent
* @constructor
*/
YAHOO.util.CustomEvent = function(type, oScope, silent) {

    /**
    * The type of event, returned to subscribers when the event fires
    * @property type
    * @type string
    */
    this.type = type;

    /**
    * The scope the the event will fire from by default.  Defaults to the window
    * obj
    * @property scope
    * @type object
    */
    this.scope = oScope || window;

    /**
    * By default all custom events are logged in the debug build, set silent
    * to true to disable logging for this event.
    * @property silent
    * @type boolean
    */
    this.silent = silent;

    /**
    * The subscribers to this event
    * @property subscribers
    * @type Subscriber[]
    */
    this.subscribers = [];

    if (!this.silent) {
    }

    // Only add subscribe events for events that are not generated by CustomEvent
    //if (oScope && (oScope.constructor != this.constructor)) {

    /*
    * Custom events provide a custom event that fires whenever there is
    * a new subscriber to the event.  This provides an opportunity to
    * handle the case where there is a non-repeating event that has
    * already fired has a new subscriber.
    *
    * type CustomEvent
    */
    //this.subscribeEvent =
    //new YAHOO.util.CustomEvent("subscribe", this, true);

    //}
};

YAHOO.util.CustomEvent.prototype = {
    /**
    * Subscribes the caller to this event
    * @method subscribe
    * @param {Function} fn       The function to execute
    * @param {Object}   obj      An object to be passed along when the event fires
    * @param {boolean}  bOverride If true, the obj passed in becomes the execution
    *                            scope of the listener
    */
    subscribe: function(fn, obj, bOverride) {
        //if (this.subscribeEvent) {
        //this.subscribeEvent.fire(fn, obj, bOverride);
        //}

        this.subscribers.push(new YAHOO.util.Subscriber(fn, obj, bOverride));
    },

    /**
    * Unsubscribes the caller from this event
    * @method unsubscribe
    * @param {Function} fn  The function to execute
    * @param {Object}   obj An object to be passed along when the event fires
    * @return {boolean} True if the subscriber was found and detached.
    */
    unsubscribe: function(fn, obj) {
        var found = false;
        for (var i = 0, len = this.subscribers.length; i < len; ++i) {
            var s = this.subscribers[i];
            if (s && s.contains(fn, obj)) {
                this._delete(i);
                found = true;
            }
        }

        return found;
    },

    /**
    * Notifies the subscribers.  The callback functions will be executed
    * from the scope specified when the event was created, and with the following
    * parameters:
    *   <pre>
    *   - The type of event
    *   - All of the arguments fire() was executed with as an array
    *   - The custom object (if any) that was passed into the subscribe() method
    *   </pre>
    * @method fire
    * @param {Array} an arbitrary set of parameters to pass to the handler
    */
    fire: function() {
        var len = this.subscribers.length;
        if (!len && this.silent) {
            return;
        }

        var args = [];

        for (var i = 0; i < arguments.length; ++i) {
            args.push(arguments[i]);
        }

        if (!this.silent) {
        }

        for (i = 0; i < len; ++i) {
            var s = this.subscribers[i];
            if (s) {
                if (!this.silent) {
                }
                var scope = (s.override) ? s.obj : this.scope;
                s.fn.call(scope, this.type, args, s.obj);
            }
        }
    },

    /**
    * Removes all listeners
    * @method unsubscribeAll
    */
    unsubscribeAll: function() {
        for (var i = 0, len = this.subscribers.length; i < len; ++i) {
            this._delete(len - 1 - i);
        }
    },

    /**
    * @method _delete
    * @private
    */
    _delete: function(index) {
        var s = this.subscribers[index];
        if (s) {
            delete s.fn;
            delete s.obj;
        }

        // delete this.subscribers[index];
        this.subscribers.splice(index, 1);
    },

    /**
    * @method toString
    */
    toString: function() {
        return "CustomEvent: " + "'" + this.type + "', " +
             "scope: " + this.scope;

    }
};

/////////////////////////////////////////////////////////////////////

/**
* Stores the subscriber information to be used when the event fires.
* @param {Function} fn       The function to execute
* @param {Object}   obj      An object to be passed along when the event fires
* @param {boolean}  bOverride If true, the obj passed in becomes the execution
*                            scope of the listener
* @class Subscriber
* @constructor
*/
YAHOO.util.Subscriber = function(fn, obj, bOverride) {

    /**
    * The callback that will be execute when the event fires
    * @property fn
    * @type function
    */
    this.fn = fn;

    /**
    * An optional custom object that will passed to the callback when
    * the event fires
    * @property obj
    * @type object
    */
    this.obj = obj || null;

    /**
    * The default execution scope for the event listener is defined when the
    * event is created (usually the object which contains the event).
    * By setting override to true, the execution scope becomes the custom
    * object passed in by the subscriber
    * @property override
    * @type boolean
    */
    this.override = (bOverride);
};

/**
* Returns true if the fn and obj match this objects properties.
* Used by the unsubscribe method to match the right subscriber.
*
* @method contains
* @param {Function} fn the function to execute
* @param {Object} obj an object to be passed along when the event fires
* @return {boolean} true if the supplied arguments match this
*                   subscriber's signature.
*/
YAHOO.util.Subscriber.prototype.contains = function(fn, obj) {
    return (this.fn == fn && this.obj == obj);
};

/**
* @method toString
*/
YAHOO.util.Subscriber.prototype.toString = function() {
    return "Subscriber { obj: " + (this.obj || "") +
           ", override: " + (this.override || "no") + " }";
};

// The first instance of Event will win if it is loaded more than once.
if (!YAHOO.util.Event) {

    /**
    * The event utility provides functions to add and remove event listeners,
    * event cleansing.  It also tries to automatically remove listeners it
    * registers during the unload event.
    * @namespace YAHOO.util
    * @class Event
    */
    YAHOO.util.Event = function() {

        /**
        * True after the onload event has fired
        * @property loadComplete
        * @type boolean
        * @private
        */
        var loadComplete = false;

        /**
        * Cache of wrapped listeners
        * @property listeners
        * @type array
        * @private
        */
        var listeners = [];

        /**
        * Listeners that will be attached during the onload event
        * @property delayedListeners
        * @type array
        * @private
        */
        var delayedListeners = [];

        /**
        * User-defined unload function that will be fired before all events
        * are detached
        * @property unloadListeners
        * @type array
        * @private
        */
        var unloadListeners = [];

        /**
        * Cache of DOM0 event handlers to work around issues with DOM2 events
        * in Safari
        * @property legacyEvents
        * @private
        */
        var legacyEvents = [];

        /**
        * Listener stack for DOM0 events
        * @property legacyHandlers
        * @private
        */
        var legacyHandlers = [];

        /**
        * The number of times to poll after window.onload.  This number is
        * increased if additional late-bound handlers are requested after
        * the page load.
        * @property retryCount
        * @private
        */
        var retryCount = 0;

        /**
        * onAvailable listeners
        * @property onAvailStack
        * @private
        */
        var onAvailStack = [];

        /**
        * Lookup table for legacy events
        * @property legacyMap
        * @private
        */
        var legacyMap = [];

        /**
        * Counter for auto id generation
        * @property counter
        * @private
        */
        var counter = 0;

        return { // PREPROCESS

            /**
            * The number of times we should look for elements that are not
            * in the DOM at the time the event is requested after the document
            * has been loaded.  The default is 200@amp;50 ms, so it will poll
            * for 10 seconds or until all outstanding handlers are bound
            * (whichever comes first).
            * @property POLL_RETRYS
            * @type int
            */
            POLL_RETRYS: 200,

            /**
            * The poll interval in milliseconds
            * @property POLL_INTERVAL
            * @type int
            */
            POLL_INTERVAL: 50,

            /**
            * Element to bind, int constant
            * @property EL
            * @type int
            */
            EL: 0,

            /**
            * Type of event, int constant
            * @property TYPE
            * @type int
            */
            TYPE: 1,

            /**
            * Function to execute, int constant
            * @property FN
            * @type int
            */
            FN: 2,

            /**
            * Function wrapped for scope correction and cleanup, int constant
            * @property WFN
            * @type int
            */
            WFN: 3,

            /**
            * Object passed in by the user that will be returned as a
            * parameter to the callback, int constant
            * @property SCOPE
            * @type int
            */
            SCOPE: 3,

            /**
            * Adjusted scope, either the element we are registering the event
            * on or the custom object passed in by the listener, int constant
            * @property ADJ_SCOPE
            * @type int
            */
            ADJ_SCOPE: 4,

            /**
            * Safari detection is necessary to work around the preventDefault
            * bug that makes it so you can't cancel a href click from the
            * handler.  There is not a capabilities check we can use here.
            * @property isSafari
            * @private
            */
            isSafari: (/Safari|Konqueror|KHTML/gi).test(navigator.userAgent),

            /**
            * IE detection needed to properly calculate pageX and pageY.
            * capabilities checking didn't seem to work because another
            * browser that does not provide the properties have the values
            * calculated in a different manner than IE.
            * @property isIE
            * @private
            */
            isIE: (!this.isSafari && !navigator.userAgent.match(/opera/gi) &&
                    navigator.userAgent.match(/msie/gi)),

            /**
            * @method addDelayedListener
            * @private
            */
            addDelayedListener: function(el, sType, fn, oScope, bOverride) {
                delayedListeners[delayedListeners.length] =
                    [el, sType, fn, oScope, bOverride];

                // If this happens after the inital page load, we need to
                // reset the poll counter so that we continue to search for
                // the element for a fixed period of time.
                if (loadComplete) {
                    retryCount = this.POLL_RETRYS;
                    this.startTimeout(0);
                    // this._tryPreloadAttach();
                }
            },

            /**
            * @method startTimeout
            * @private
            */
            startTimeout: function(interval) {
                var i = (interval || interval === 0) ? interval : this.POLL_INTERVAL;
                var self = this;
                var callback = function() { self._tryPreloadAttach(); };
                this.timeout = setTimeout(callback, i);
            },

            /**
            * Executes the supplied callback when the item with the supplied
            * id is found.  This is meant to be used to execute behavior as
            * soon as possible as the page loads.  If you use this after the
            * initial page load it will poll for a fixed time for the element.
            * The number of times it will poll and the frequency are
            * configurable.  By default it will poll for 10 seconds.
            *
            * @method onAvailable
            *
            * @param {string}   p_id the id of the element to look for.
            * @param {function} p_fn what to execute when the element is found.
            * @param {object}   p_obj an optional object to be passed back as
            *                   a parameter to p_fn.
            * @param {boolean}  p_override If set to true, p_fn will execute
            *                   in the scope of p_obj
            *
            */
            onAvailable: function(p_id, p_fn, p_obj, p_override) {
                onAvailStack.push({ id: p_id,
                    fn: p_fn,
                    obj: p_obj,
                    override: p_override
                });

                retryCount = this.POLL_RETRYS;
                this.startTimeout(0);
                // this._tryPreloadAttach();
            },

            /**
            * Appends an event handler
            *
            * @method addListener
            *
            * @param {Object}   el        The html element to assign the
            *                             event to
            * @param {String}   sType     The type of event to append
            * @param {Function} fn        The method the event invokes
            * @param {Object}   oScope    An arbitrary object that will be
            *                             passed as a parameter to the handler
            * @param {boolean}  bOverride If true, the obj passed in becomes
            *                             the execution scope of the listener
            * @return {boolean} True if the action was successful or defered,
            *                        false if one or more of the elements
            *                        could not have the event bound to it.
            */
            addListener: function(el, sType, fn, oScope, bOverride) {

                if (!fn || !fn.call) {
                    return false;
                }

                // The el argument can be an array of elements or element ids.
                if (this._isValidCollection(el)) {
                    var ok = true;
                    for (var i = 0, len = el.length; i < len; ++i) {
                        ok = (this.on(el[i],
                                       sType,
                                       fn,
                                       oScope,
                                       bOverride) && ok);
                    }
                    return ok;

                } else if (typeof el == "string") {
                    var oEl = this.getEl(el);
                    // If the el argument is a string, we assume it is
                    // actually the id of the element.  If the page is loaded
                    // we convert el to the actual element, otherwise we
                    // defer attaching the event until onload event fires

                    // check to see if we need to delay hooking up the event
                    // until after the page loads.
                    if (loadComplete && oEl) {
                        el = oEl;
                    } else {
                        // defer adding the event until onload fires
                        this.addDelayedListener(el,
                                                sType,
                                                fn,
                                                oScope,
                                                bOverride);

                        return true;
                    }
                }

                // Element should be an html element or an array if we get
                // here.
                if (!el) {
                    return false;
                }

                // we need to make sure we fire registered unload events
                // prior to automatically unhooking them.  So we hang on to
                // these instead of attaching them to the window and fire the
                // handles explicitly during our one unload event.
                if ("unload" == sType && oScope !== this) {
                    unloadListeners[unloadListeners.length] =
                            [el, sType, fn, oScope, bOverride];
                    return true;
                }

                // if the user chooses to override the scope, we use the custom
                // object passed in, otherwise the executing scope will be the
                // HTML element that the event is registered on
                var scope = (bOverride) ? oScope : el;

                // wrap the function so we can return the oScope object when
                // the event fires;
                var wrappedFn = function(e) {
                    return fn.call(scope, YAHOO.util.Event.getEvent(e),
                                oScope);
                };

                var li = [el, sType, fn, wrappedFn, scope];
                var index = listeners.length;
                // cache the listener so we can try to automatically unload
                listeners[index] = li;

                if (this.useLegacyEvent(el, sType)) {
                    var legacyIndex = this.getLegacyIndex(el, sType);

                    // Add a new dom0 wrapper if one is not detected for this
                    // element
                    if (legacyIndex == -1 ||
                                el != legacyEvents[legacyIndex][0]) {

                        legacyIndex = legacyEvents.length;
                        legacyMap[el.id + sType] = legacyIndex;

                        // cache the signature for the DOM0 event, and
                        // include the existing handler for the event, if any
                        legacyEvents[legacyIndex] =
                            [el, sType, el["on" + sType]];
                        legacyHandlers[legacyIndex] = [];

                        el["on" + sType] =
                            function(e) {
                                YAHOO.util.Event.fireLegacyEvent(
                                    YAHOO.util.Event.getEvent(e), legacyIndex);
                            };
                    }

                    // add a reference to the wrapped listener to our custom
                    // stack of events
                    //legacyHandlers[legacyIndex].push(index);
                    legacyHandlers[legacyIndex].push(li);

                    // DOM2 Event model
                } else if (el.addEventListener) {
                    el.addEventListener(sType, wrappedFn, false);
                    // IE
                } else if (el.attachEvent) {
                    el.attachEvent("on" + sType, wrappedFn);
                }

                return true;

            },

            /**
            * When using legacy events, the handler is routed to this object
            * so we can fire our custom listener stack.
            * @method fireLegacyEvent
            * @private
            */
            fireLegacyEvent: function(e, legacyIndex) {
                var ok = true;

                var le = legacyHandlers[legacyIndex];
                for (var i = 0, len = le.length; i < len; ++i) {
                    var li = le[i];
                    if (li && li[this.WFN]) {
                        var scope = li[this.ADJ_SCOPE];
                        var ret = li[this.WFN].call(scope, e);
                        ok = (ok && ret);
                    }
                }

                return ok;
            },

            /**
            * Returns the legacy event index that matches the supplied
            * signature
            * @method getLegacyIndex
            * @private
            */
            getLegacyIndex: function(el, sType) {
                var key = this.generateId(el) + sType;
                if (typeof legacyMap[key] == "undefined") {
                    return -1;
                } else {
                    return legacyMap[key];
                }
            },

            /**
            * Logic that determines when we should automatically use legacy
            * events instead of DOM2 events.
            * @method useLegacyEvent
            * @private
            */
            useLegacyEvent: function(el, sType) {
                if (!el.addEventListener && !el.attachEvent) {
                    return true;
                } else if (this.isSafari) {
                    if ("click" == sType || "dblclick" == sType) {
                        return true;
                    }
                }
                return false;
            },

            /**
            * Removes an event handler
            *
            * @method removeListener
            *
            * @param {Object} el the html element or the id of the element to
            * assign the event to.
            * @param {String} sType the type of event to remove
            * @param {Function} fn the method the event invokes
            * @return {boolean} true if the unbind was successful, false
            * otherwise
            */
            removeListener: function(el, sType, fn, index) {

                if (!fn || !fn.call) {
                    return false;
                }

                var i, len;

                // The el argument can be a string
                if (typeof el == "string") {
                    el = this.getEl(el);
                    // The el argument can be an array of elements or element ids.
                } else if (this._isValidCollection(el)) {
                    var ok = true;
                    for (i = 0, len = el.length; i < len; ++i) {
                        ok = (this.removeListener(el[i], sType, fn) && ok);
                    }
                    return ok;
                }

                if ("unload" == sType) {

                    for (i = 0, len = unloadListeners.length; i < len; i++) {
                        var li = unloadListeners[i];
                        if (li &&
                            li[0] == el &&
                            li[1] == sType &&
                            li[2] == fn) {
                            unloadListeners.splice(i, 1);
                            return true;
                        }
                    }

                    return false;
                }

                var cacheItem = null;

                //var index = arguments[3];

                if ("undefined" == typeof index) {
                    index = this._getCacheIndex(el, sType, fn);
                }

                if (index >= 0) {
                    cacheItem = listeners[index];
                }

                if (!el || !cacheItem) {
                    return false;
                }

                if (this.useLegacyEvent(el, sType)) {
                    var legacyIndex = this.getLegacyIndex(el, sType);
                    var llist = legacyHandlers[legacyIndex];
                    if (llist) {
                        for (i = 0, len = llist.length; i < len; ++i) {
                            li = llist[i];
                            if (li &&
                                li[this.EL] == el &&
                                li[this.TYPE] == sType &&
                                li[this.FN] == fn) {
                                llist.splice(i, 1);
                            }
                        }
                    }

                } else if (el.removeEventListener) {
                    el.removeEventListener(sType, cacheItem[this.WFN], false);
                } else if (el.detachEvent) {
                    el.detachEvent("on" + sType, cacheItem[this.WFN]);
                }

                // removed the wrapped handler
                delete listeners[index][this.WFN];
                delete listeners[index][this.FN];
                listeners.splice(index, 1);

                return true;

            },

            /**
            * Returns the event's target element
            * @method getTarget
            * @param {Event} ev the event
            * @param {boolean} resolveTextNode when set to true the target's
            *                  parent will be returned if the target is a
            *                  text node.  @deprecated, the text node is
            *                  now resolved automatically
            * @return {HTMLElement} the event's target
            */
            getTarget: function(ev, resolveTextNode) {
                var t = ev.target || ev.srcElement;
                return this.resolveTextNode(t);
            },

            /**
            * In some cases, some browsers will return a text node inside
            * the actual element that was targeted.  This normalizes the
            * return value for getTarget and getRelatedTarget.
            * @method resolveTextNode
            * @param {HTMLElement} node to resolve
            * @return  the normized node
            */
            resolveTextNode: function(node) {
                if (node && node.nodeName &&
                        "#TEXT" == node.nodeName.toUpperCase()) {
                    return node.parentNode;
                } else {
                    return node;
                }
            },

            /**
            * Returns the event's pageX
            * @method getPageX
            * @param {Event} ev the event
            * @return {int} the event's pageX
            */
            getPageX: function(ev) {
                var x = ev.pageX;
                if (!x && 0 !== x) {
                    x = ev.clientX || 0;

                    if (this.isIE) {
                        x += this._getScrollLeft();
                    }
                }

                return x;
            },

            /**
            * Returns the event's pageY
            * @method getPageY
            * @param {Event} ev the event
            * @return {int} the event's pageY
            */
            getPageY: function(ev) {
                var y = ev.pageY;
                if (!y && 0 !== y) {
                    y = ev.clientY || 0;

                    if (this.isIE) {
                        y += this._getScrollTop();
                    }
                }

                return y;
            },

            /**
            * Returns the pageX and pageY properties as an indexed array.
            * @method getXY
            * @type int[]
            */
            getXY: function(ev) {
                return [this.getPageX(ev), this.getPageY(ev)];
            },

            /**
            * Returns the event's related target
            * @method getRelatedTarget
            * @param {Event} ev the event
            * @return {HTMLElement} the event's relatedTarget
            */
            getRelatedTarget: function(ev) {
                var t = ev.relatedTarget;
                if (!t) {
                    if (ev.type == "mouseout") {
                        t = ev.toElement;
                    } else if (ev.type == "mouseover") {
                        t = ev.fromElement;
                    }
                }

                return this.resolveTextNode(t);
            },

            /**
            * Returns the time of the event.  If the time is not included, the
            * event is modified using the current time.
            * @method getTime
            * @param {Event} ev the event
            * @return {Date} the time of the event
            */
            getTime: function(ev) {
                if (!ev.time) {
                    var t = new Date().getTime();
                    try {
                        ev.time = t;
                    } catch (e) {
                        // can't set the time property
                        return t;
                    }
                }

                return ev.time;
            },

            /**
            * Convenience method for stopPropagation + preventDefault
            * @method stopEvent
            * @param {Event} ev the event
            */
            stopEvent: function(ev) {
                this.stopPropagation(ev);
                this.preventDefault(ev);
            },

            /**
            * Stops event propagation
            * @method stopPropagation
            * @param {Event} ev the event
            */
            stopPropagation: function(ev) {
                if (ev.stopPropagation) {
                    ev.stopPropagation();
                } else {
                    ev.cancelBubble = true;
                }
            },

            /**
            * Prevents the default behavior of the event
            * @method preventDefault
            * @param {Event} ev the event
            */
            preventDefault: function(ev) {
                if (ev.preventDefault) {
                    ev.preventDefault();
                } else {
                    ev.returnValue = false;
                }
            },

            /**
            * Finds the event in the window object, the caller's arguments, or
            * in the arguments of another method in the callstack.  This is
            * executed automatically for events registered through the event
            * manager, so the implementer should not normally need to execute
            * this function at all.
            * @method getEvent
            * @param {Event} the event parameter from the handler
            * @return {Event} the event
            */
            getEvent: function(e) {
                var ev = e || window.event;

                if (!ev) {
                    var c = this.getEvent.caller;
                    while (c) {
                        ev = c.arguments[0];
                        if (ev && Event == ev.constructor) {
                            break;
                        }
                        c = c.caller;
                    }
                }

                return ev;
            },

            /**
            * Returns the charcode for an event
            * @method getCharCode
            * @param {Event} ev the event
            * @return {int} the event's charCode
            */
            getCharCode: function(ev) {
                return ev.charCode || ((ev.type == "keypress") ? ev.keyCode : 0);
            },

            /**
            * Locating the saved event handler data by function ref
            *
            * @method _getCacheIndex
            * @private
            */
            _getCacheIndex: function(el, sType, fn) {
                for (var i = 0, len = listeners.length; i < len; ++i) {
                    var li = listeners[i];
                    if (li &&
                         li[this.FN] == fn &&
                         li[this.EL] == el &&
                         li[this.TYPE] == sType) {
                        return i;
                    }
                }

                return -1;
            },

            /**
            * Generates an unique ID for the element if it does not already
            * have one.
            * @method generateId
            * @param el the element
            * @return {string} the id of the element
            */
            generateId: function(el) {
                var id = el.id;

                if (!id) {
                    id = "yuievtautoid-" + counter;
                    ++counter;
                    el.id = id;
                }

                return id;
            },

            /**
            * We want to be able to use getElementsByTagName as a collection
            * to attach a group of events to.  Unfortunately, different
            * browsers return different types of collections.  This function
            * tests to determine if the object is array-like.  It will also
            * fail if the object is an array, but is empty.
            * @method _isValidCollection
            * @param o the object to test
            * @return {boolean} true if the object is array-like and populated
            * @private
            */
            _isValidCollection: function(o) {

                return (o && // o is something
                         o.length && // o is indexed
                         typeof o != "string" && // o is not a string
                         !o.tagName && // o is not an HTML element
                         !o.alert && // o is not a window
                         typeof o[0] != "undefined");

            },

            /**
            * @private
            * @property elCache
            * DOM element cache
            */
            elCache: {},

            /**
            * We cache elements bound by id because when the unload event
            * fires, we can no longer use document.getElementById
            * @method getEl
            * @private
            */
            getEl: function(id) {
                return document.getElementById(id);
            },

            /**
            * Clears the element cache
            * @deprecated
            * @private
            */
            clearCache: function() { },

            /**
            * hook up any deferred listeners
            * @method _load
            * @private
            */
            _load: function(e) {
                loadComplete = true;
                var EU = YAHOO.util.Event;
                EU._simpleRemove(window, "load", EU._load);
            },

            /**
            * Polling function that runs before the onload event fires,
            * attempting to attach to DOM Nodes as soon as they are
            * available
            * @method _tryPreloadAttach
            * @private
            */
            _tryPreloadAttach: function() {

                if (this.locked) {
                    return false;
                }

                this.locked = true;

                // keep trying until after the page is loaded.  We need to
                // check the page load state prior to trying to bind the
                // elements so that we can be certain all elements have been
                // tested appropriately
                var tryAgain = !loadComplete;
                if (!tryAgain) {
                    tryAgain = (retryCount > 0);
                }

                // Delayed listeners
                var stillDelayed = [];

                for (var i = 0, len = delayedListeners.length; i < len; ++i) {
                    var d = delayedListeners[i];
                    // There may be a race condition here, so we need to
                    // verify the array element is usable.
                    if (d) {

                        // el will be null if document.getElementById did not
                        // work
                        var el = this.getEl(d[this.EL]);

                        if (el) {
                            this.on(el, d[this.TYPE], d[this.FN],
                                    d[this.SCOPE], d[this.ADJ_SCOPE]);
                            delete delayedListeners[i];
                        } else {
                            stillDelayed.push(d);
                        }
                    }
                }

                delayedListeners = stillDelayed;

                // onAvailable
                var notAvail = [];
                for (i = 0, len = onAvailStack.length; i < len; ++i) {
                    var item = onAvailStack[i];
                    if (item) {
                        el = this.getEl(item.id);

                        if (el) {
                            var scope = (item.override) ? item.obj : el;
                            item.fn.call(scope, item.obj);
                            delete onAvailStack[i];
                        } else {
                            notAvail.push(item);
                        }
                    }
                }

                retryCount = (stillDelayed.length === 0 &&
                                    notAvail.length === 0) ? 0 : retryCount - 1;

                if (tryAgain) {
                    this.startTimeout();
                }

                this.locked = false;

                return true;

            },

            /**
            * Removes all listeners attached to the given element via addListener.
            * Optionally, the node's children can also be purged.
            * Optionally, you can specify a specific type of event to remove.
            * @method purgeElement
            * @param {HTMLElement} el the element to purge
            * @param {boolean} recurse recursively purge this element's children
            * as well.  Use with caution.
            * @param {string} sType optional type of listener to purge. If
            * left out, all listeners will be removed
            */
            purgeElement: function(el, recurse, sType) {
                var elListeners = this.getListeners(el, sType);
                if (elListeners) {
                    for (var i = 0, len = elListeners.length; i < len; ++i) {
                        var l = elListeners[i];
                        // can't use the index on the changing collection
                        //this.removeListener(el, l.type, l.fn, l.index);
                        this.removeListener(el, l.type, l.fn);
                    }
                }

                if (recurse && el && el.childNodes) {
                    for (i = 0, len = el.childNodes.length; i < len; ++i) {
                        this.purgeElement(el.childNodes[i], recurse, sType);
                    }
                }
            },

            /**
            * Returns all listeners attached to the given element via addListener.
            * Optionally, you can specify a specific type of event to return.
            * @method getListeners
            * @param el {HTMLElement} the element to inspect
            * @param sType {string} optional type of listener to return. If
            * left out, all listeners will be returned
            * @return {Object} the listener. Contains the following fields:
            *    type:   (string)   the type of event
            *    fn:     (function) the callback supplied to addListener
            *    obj:    (object)   the custom object supplied to addListener
            *    adjust: (boolean)  whether or not to adjust the default scope
            *    index:  (int)      its position in the Event util listener cache
            */
            getListeners: function(el, sType) {
                var elListeners = [];
                if (listeners && listeners.length > 0) {
                    for (var i = 0, len = listeners.length; i < len; ++i) {
                        var l = listeners[i];
                        if (l && l[this.EL] === el &&
                                (!sType || sType === l[this.TYPE])) {
                            elListeners.push({
                                type: l[this.TYPE],
                                fn: l[this.FN],
                                obj: l[this.SCOPE],
                                adjust: l[this.ADJ_SCOPE],
                                index: i
                            });
                        }
                    }
                }

                return (elListeners.length) ? elListeners : null;
            },

            /**
            * Removes all listeners registered by pe.event.  Called
            * automatically during the unload event.
            * @method _unload
            * @private
            */
            _unload: function(e) {

                var EU = YAHOO.util.Event;

                for (var i = 0, len = unloadListeners.length; i < len; ++i) {
                    var l = unloadListeners[i];
                    if (l) {
                        var scope = (l[EU.ADJ_SCOPE]) ? l[EU.SCOPE] : window;
                        l[EU.FN].call(scope, EU.getEvent(e), l[EU.SCOPE]);
                        delete unloadListeners[i];
                        l = null;
                    }
                }

                if (listeners && listeners.length > 0) {
                    //for (i=0,len=listeners.length; i<len ; ++i) {
                    var j = listeners.length;
                    while (j) {
                        var index = j - 1;
                        l = listeners[index];
                        if (l) {
                            EU.removeListener(l[EU.EL], l[EU.TYPE],
                                    l[EU.FN], index);
                        }

                        l = null;

                        j = j - 1;
                    }

                    EU.clearCache();
                }

                for (i = 0, len = legacyEvents.length; i < len; ++i) {
                    // dereference the element
                    delete legacyEvents[i][0];
                    // delete the array item
                    delete legacyEvents[i];
                }

                EU._simpleRemove(window, "unload", EU._unload);

            },

            /**
            * Returns scrollLeft
            * @method _getScrollLeft
            * @private
            */
            _getScrollLeft: function() {
                return this._getScroll()[1];
            },

            /**
            * Returns scrollTop
            * @method _getScrollTop
            * @private
            */
            _getScrollTop: function() {
                return this._getScroll()[0];
            },

            /**
            * Returns the scrollTop and scrollLeft.  Used to calculate the
            * pageX and pageY in Internet Explorer
            * @method _getScroll
            * @private
            */
            _getScroll: function() {
                var dd = document.documentElement, db = document.body;
                if (dd && (dd.scrollTop || dd.scrollLeft)) {
                    return [dd.scrollTop, dd.scrollLeft];
                } else if (db) {
                    return [db.scrollTop, db.scrollLeft];
                } else {
                    return [0, 0];
                }
            },

            /**
            * Adds a DOM event directly without the caching, cleanup, scope adj, etc
            *
            * @param el the elment to bind the handler to
            * @param {string} sType the type of event handler
            * @param {function} fn the callback to invoke
            * @param {boolen} capture or bubble phase
            * @private
            */
            _simpleAdd: function(el, sType, fn, capture) {
                if (el.addEventListener) {
                    el.addEventListener(sType, fn, (capture));
                } else if (el.attachEvent) {
                    el.attachEvent("on" + sType, fn);
                }
            },

            /**
            * Basic remove listener
            *
            * @param el the elment to bind the handler to
            * @param {string} sType the type of event handler
            * @param {function} fn the callback to invoke
            * @param {boolen} capture or bubble phase
            * @private
            */
            _simpleRemove: function(el, sType, fn, capture) {
                if (el.removeEventListener) {
                    el.removeEventListener(sType, fn, (capture));
                } else if (el.detachEvent) {
                    el.detachEvent("on" + sType, fn);
                }
            }
        };

    } ();

    /**
    * YAHOO.util.Event.on is an alias for addListener
    * @method on
    * @see addListener
    */
    YAHOO.util.Event.on = YAHOO.util.Event.addListener;

    if (document && document.body) {
        YAHOO.util.Event._load();
    } else {
        YAHOO.util.Event._simpleAdd(window, "load", YAHOO.util.Event._load);
    }
    YAHOO.util.Event._simpleAdd(window, "unload", YAHOO.util.Event._unload);
    YAHOO.util.Event._tryPreloadAttach();
}


/***************************************************************
***************************************************************
include/js/ajax/main.js
***************************************************************
**************************************************************/

// Tennis Australia - Ajax Calendar Component calendar.js v1.0.0, Thur Dec 07 12:55:00
// Copyright (c) 2006 Atomic Media (http://www.atomicmedia.com.au)

var rootURL = 'http://www.tennis.com.au/';

function initAjaxComponents(siteid, pageid) {
    // VIDEO
    //if (document.getElementById('divFlashVideo'))
    //	setvideo('clips/emma.flv', '230', 'pause()');

    // NEWS
    if (document.getElementById('tnews'))
        initNews(0, 0);

    // PHOTOS
    if (document.getElementById('contphotos'))
        initPhotos();

    // OUR PARTNERS
    if (document.getElementById('partner'))
        initPartners();

    // LATEST NEWS (SMALL NEWS IMAGE SCROLLER)
    if (document.getElementById('latestnews'))
        getLatestNewsXML();

    // LATEST PHOTO GALLERIES (SMALL PHOTO GALLERY SCROLLER)
    if (document.getElementById('latestphotos'))
        getLatestPhotoGalleryXML();

    // MORE NEWS (NEWS IMAGE SCROLLER WITH NEWS LINKS UNDERNEATH IMAGE)
    if (document.getElementById('morenewsimg'))
        getMoreNewsXML();

    // CALENDAR
    if (document.getElementById('divtour'))
        getCalendarXML(1, 1);

    // PHOTO GALLERY
    if ($('gallery1'))
        initPhotoGallery();

    // AUDIO GALLERY
    if ($('firstAudio'))
        initAudioGallery();

    //if ($('firstVideo'))
        //tennitenninitVideoGallery();
}


function getAjaxMessagingComponent() {

    // MESSAGES
    if (document.getElementById('spInboxMsg'))
        getInboxMessage();
}


function submitOnEnterGlobalSearch(e) {
    var k = (e.which) ? e.which : e.keyCode;

    if (k == 13) {
        if (e && e.preventDefault)
            e.preventDefault();
        //e.cancelable = true;
        //e.bubbles = false;
        //e.cancelBubble = true;
        e.returnValue = false;
        e.cancel = true;
        searchBloxGo(document.frmSearch.cname.value, document.frmSearch.query.value);
    }
}

function searchField() {
    if (document.frmSearch.query.value == '') {
        document.frmSearch.query.value = 'Search';
    }
}

function locationField() {
    if (document.frmHaveAHit.SearchValue.value == '') {
        document.frmHaveAHit.SearchValue.value = 'Location';
    }
}

function FirstnameField() {
    if (document.frmSignup.txtname_nav.value == '') {
        document.frmSignup.txtname_nav.value = 'First';
    }

}

function SurnameField() {
    if (document.frmSignup.txtsurname_nav.value == '') {
        document.frmSignup.txtsurname_nav.value = 'Last';
    }

}

function EmailField() {
    if (document.frmSignup.txtemail_nav.value == '') {
        document.frmSignup.txtemail_nav.value = 'Email';
    }

}

function submitOnEnterGlobalSearchRHS(e) {
    var k = (e.which) ? e.which : e.keyCode;

    if (k == 13) {
        if (e && e.preventDefault)
            e.preventDefault();
        //e.cancelable = true;
        //e.bubbles = false;
        //e.cancelBubble = true;
        e.returnValue = false;
        e.cancel = true;
        searchBloxGoWithType(document.frmSearchNews.cname.value, document.frmSearchNews.query.value, document.frmSearchNews.SearchType.value);
    }
}


function searchBloxGo(strName, strQuery) {
    var strURL = "http://search.atomicmedia.com:8080/searchblox/servlet/SearchServlet?sort=relevance&cname=" + strName + "&query=" + strQuery;
    //var strURL = "http://www.tennis.com.au:8080/searchblox/servlet/SearchServlet?sort=relevance&cname=" + strName + "&query=" + strQuery;
    //var strURL = "http://www.google.com.au/";
    /*if (rootURL.indexOf('www.tennis.com.au') != -1 && strURL.indexOf('www.tennis.com.au/pages/') == -1 && strURL.indexOf('http://') != -1 && strURL.indexOf('www.tennis.com.au:8080/searchblox/') == -1)
    var strHTML = '<iframe id="myiframe" style="border:none;width:100%;" name="myiframe" width="100%" height="0px" onload="DYNIFS.resize(\'myiframe\');" valign="left" align="left" frameborder="0" marginheight="0" marginwidth="0" src="' + strURL + '"></iframe>';
    else*/
    var strHTML = '<iframe valign="left" align="left" frameborder="0" marginheight="0" marginwidth="0" width="100%" height="1360px" src="' + strURL + '"></iframe>';
    if ($('maindiv')) {
        $('maindiv').style.height = "1222";
        $('maindiv').innerHTML = '';
        $('maindiv').innerHTML = strHTML;
    }
}

function searchBloxGoWithType(strName, strQuery, strType) {
    var strURL = "http://search.atomicmedia.com:8080/searchblox/servlet/SearchServlet?sort=relevance&cname=" + strName + "&query=" + strQuery + "&SearchType=" + strType;
    //var strURL = "http://www.google.com.au/";
    /*if (rootURL.indexOf('www.tennis.com.au') != -1 && strURL.indexOf('www.tennis.com.au/pages/') == -1 && strURL.indexOf('http://') != -1 && strURL.indexOf('www.tennis.com.au:8080/searchblox/') == -1)
    var strHTML = '<iframe id="myiframe" style="border:none;width:100%;" name="myiframe" width="100%" height="0px" onload="DYNIFS.resize(\'myiframe\');" valign="left" align="left" frameborder="0" marginheight="0" marginwidth="0" src="' + strURL + '"></iframe>';
    else*/
    var strHTML = '<iframe valign="left" align="left" frameborder="0" marginheight="0" marginwidth="0" width="100%" height="1360px" src="' + strURL + '"></iframe>';
    if ($('maindiv')) {
        $('maindiv').style.height = "1360px";
        $('maindiv').innerHTML = '';
        $('maindiv').innerHTML = strHTML;
    }
}

function genericLoadPageInIframe(strURL) {
    /*if (rootURL.indexOf('www.tennis.com.au') != -1 && strURL.indexOf('www.tennis.com.au/pages/') == -1 && strURL.indexOf('http://') != -1 && strURL.indexOf('www.tennis.com.au:8080/searchblox/') == -1)
    var strHTML = '<iframe id="myiframe" style="border:none;width:100%;" name="myiframe" width="100%" height="0px" onload="DYNIFS.resize(\'myiframe\');" valign="left" align="left" frameborder="0" marginheight="0" marginwidth="0" src="' + strURL + '"></iframe>';
    else*/
    var strHTML = '<iframe valign="left" align="left" frameborder="0" marginheight="0" marginwidth="0" width="643" height="1800" src="' + strURL + '"></iframe>';
    if ($('maindiv')) {
        $('maindiv').innerHTML = '';
        $('maindiv').innerHTML = strHTML;
    }
}

function viewTournamentLink(strURL) {
    /*if (rootURL.indexOf('www.tennis.com.au') != -1 && strURL.indexOf('www.tennis.com.au/pages/') == -1 && strURL.indexOf('http://') != -1 && strURL.indexOf('www.tennis.com.au:8080/searchblox/') == -1)
    var strHTML = '<iframe id="myiframe" style="border:none;width:100%;" name="myiframe" width="100%" height="0px" onload="DYNIFS.resize(\'myiframe\');" valign="left" align="left" frameborder="0" marginheight="0" marginwidth="0" src="' + strURL + '"></iframe>';
    else*/
    var strHTML = '<iframe valign="left" align="left" frameborder="0" marginheight="0" marginwidth="0" width="643" height="800" src="' + strURL + '"></iframe>';
    if ($('maindiv')) {
        $('maindiv').innerHTML = '';
        $('maindiv').innerHTML = strHTML;
    }
}

// DEPRECATED
function submitOnEnter(e, strSubmitButtonID) {
    if (e.keyCode == 13) {
        e.returnValue = false;
        e.cancel = true;
        window.top.eval(strSubmitButtonID).click();
    }
}
// END

function gTracker(arg) {
    try {
        urchinTracker(arg);
    }
    catch (err) {
        //alert(err);
    }
}

/***************************************************************
***************************************************************
include/js/ajax/ajax.js
***************************************************************
**************************************************************/

// Tennis Australia - Ajax Components ajax.js v1.0.0, Wed Dec 13 3:50:00
// Copyright (c) 2006 Atomic Media (http://www.atomicmedia.com.au)
/////////////////////////////////////////////////////////////////////////////
//
//	function initNews()
//	function initPhotos()
//	function initPartners()
//
/////////////////////////////////////////////////////////////////////////////

//NEWS - AJAX COMPONENT
/////////////////////////////////////////////////////////////////////////////
//Home Page and News Landing Page - Rotating News

// time = time for periodical execution (seconds)
var time = 10;

var pe;
var pe2;

var exec = 0;
var x = 0;
var ids = ["news1", "news2", "news3", "news4"];

strPhotos = new String();
strPopularPhotos = new String();

indexArray = new Array(0, 5, 10, 15);
newsArray = new Array();
viewedArray = new Array();
emailedArray = new Array();

logoimg = new Array();
logourl = new Array();
logoname = new Array();

//Initiate News Component
function initNews(v, e) {
    if (exec != 0) {
        clearbt();
    }
    x = 0;
    if (v == 1)
        e = 0;
    if (e == 1)
        v = 0;
    var sUrl = 'AjaxNewsXML.aspx?id=4&PageId=122&HandlerId=300&MostEmailed=' + e + '&MostViewed=' + v;
    //alert(sUrl);
    YAHOO.util.Connect.initHeader("Content-Type", "application/xml");
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: successHandler, failure: failureHandler });
}

//Success reading the XML file
//Displaying the 4 "small articles" and the 3 "more links"
//The first small article is the default for the large article area 
function successHandler(o) {

    xmlObj = o.responseXML.documentElement;

    var lines = xmlObj.getElementsByTagName('News').length;

    var noimage = "RDM39059.6785644907";
    var cont = 0;
    var z = 0;
    for (var index = 0; index < lines; index++) {
        for (var i = 0; i < 5; i++) {

            if (z == 0) {
                newsArray[cont] = xmlObj.getElementsByTagName('News').item(index).getAttribute("BodyImage");
                if ((newsArray[cont] == "") || (newsArray[cont] == " ") || (newsArray[cont] == "null") || (newsArray[cont] == "NULL")) {
                    newsArray[cont] = noimage;
                }
            }
            else if (z == 1) {
                newsArray[cont] = xmlObj.getElementsByTagName('News').item(index).getAttribute("Title");
            }
            else if (z == 2) {
                newsArray[cont] = xmlObj.getElementsByTagName('News').item(index).getAttribute("NewsDate");
            }
            else if (z == 3) {
                newsArray[cont] = xmlObj.getElementsByTagName('News').item(index).getAttribute("ShortBody");
            }
            else if (z == 4) {
                newsArray[cont] = xmlObj.getElementsByTagName('News').item(index).getAttribute("NewsID");
            }

            cont++;
            z++;
            if (z > 4) {
                z = 0;
            }
        }
    }

    //$('news1').innerHTML = '<img alt="' + newsArray[1] + '" src="image.aspx?assetid=' + newsArray[0] + '&amp;blobType=blob_thumbnail_small" width="140" height="93" border="0" onmouseover="overEffect(this);" style="display:block;" /><span onmouseover="under(this,1)" onmouseout="under(this,0)">' + newsArray[1] + '</span>';
    //$('news2').innerHTML = '<img alt="' + newsArray[6] + '" src="image.aspx?assetid=' + newsArray[5] + '&amp;blobType=blob_thumbnail_small" width="140" height="93" border="0" onmouseover="overEffect(this);" style="display:block;" /><span onmouseover="under(this,1)" onmouseout="under(this,0)">' + newsArray[6] + '</div>';
    //$('news3').innerHTML = '<img alt="' + newsArray[11] + '" src="image.aspx?assetid=' + newsArray[10] + '&amp;blobType=blob_thumbnail_small" width="140" height="93" border="0" onmouseover="overEffect(this);" style="display:block;" /><span onmouseover="under(this,1)" onmouseout="under(this,0)">' + newsArray[11] + '</span>';
    //$('news4').innerHTML = '<img alt="' + newsArray[16] + '" src="image.aspx?assetid=' + newsArray[15] + '&amp;blobType=blob_thumbnail_small" width="140" height="93" border="0" onmouseover="overEffect(this);" style="display:block;" /><span onmouseover="under(this,1)" onmouseout="under(this,0)">' + newsArray[16] + '</span>';
    //$('news5').innerHTML = '<span class="newstxt">More News</span><br><img src="images/taAssets/arrow_grey2.gif" class="arrowgrey"><a class="normal" href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[24] + '">' + newsArray[21] + '</a>';
    //$('news6').innerHTML = '<img src="images/taAssets/arrow_grey2.gif" class="arrowgrey"><a class="normal" href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[29] + '">' + newsArray[26] + '</a>';
    //$('news7').innerHTML = '<img src="images/taAssets/arrow_grey2.gif" class="arrowgrey"><a class="normal" href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[34] + '">' + newsArray[31] + '</a>';

    $('news1').innerHTML = '<table cellpadding="0" cellspacing="0" border="0" valign="top" width="142"><tr><td width="0" background="lside-10x1024.jpg"></td><td><img alt="' + newsArray[1] + '" src="image.aspx?assetid=' + newsArray[0] + '&amp;blobType=blob_thumbnail_small" width="140" height="93" border="0" onmouseover="overEffect(this);" style="display:block;" /></td><td width="3" background="/pages/images/taAssets/vdrop-20x1024.jpg"></td></tr><tr><td width="0"></td><td height="4" background="/pages/images/taAssets/hdrop-1024x20.jpg"></td><td height="4" background="/pages/images/taAssets/cdrop-20x20.jpg"></td></tr></table><span style="position:relative;top:-2px;line-height:13px;" onmouseover="under(this,1)" onmouseout="under(this,0)">' + newsArray[1] + '</span>';
    $('news2').innerHTML = '<table cellpadding="0" cellspacing="0" border="0" valign="top" width="142"><tr><td width="0" background="lside-10x1024.jpg"></td><td><img alt="' + newsArray[6] + '" src="image.aspx?assetid=' + newsArray[5] + '&amp;blobType=blob_thumbnail_small" width="140" height="93" border="0" onmouseover="overEffect(this);" style="display:block;" /></td><td width="3" background="/pages/images/taAssets/vdrop-20x1024.jpg"></td></tr><tr><td width="0"></td><td height="4" background="/pages/images/taAssets/hdrop-1024x20.jpg"></td><td height="4" background="/pages/images/taAssets/cdrop-20x20.jpg"></td></tr></table><span style="position:relative;top:-2px;line-height:13px;" onmouseover="under(this,1)" onmouseout="under(this,0)">' + newsArray[6] + '</span>';
    $('news3').innerHTML = '<table cellpadding="0" cellspacing="0" border="0" valign="top" width="142"><tr><td width="0" background="lside-10x1024.jpg"></td><td><img alt="' + newsArray[11] + '" src="image.aspx?assetid=' + newsArray[10] + '&amp;blobType=blob_thumbnail_small" width="140" height="93" border="0" onmouseover="overEffect(this);" style="display:block;" /></td><td width="3" background="/pages/images/taAssets/vdrop-20x1024.jpg"></td></tr><tr><td width="0"></td><td height="4" background="/pages/images/taAssets/hdrop-1024x20.jpg"></td><td height="4" background="/pages/images/taAssets/cdrop-20x20.jpg"></td></tr></table><span style="position:relative;top:-2px;line-height:13px;" onmouseover="under(this,1)" onmouseout="under(this,0)">' + newsArray[11] + '</span>';
    $('news4').innerHTML = '<table cellpadding="0" cellspacing="0" border="0" valign="top" width="142"><tr><td width="0" background="lside-10x1024.jpg"></td><td><img alt="' + newsArray[16] + '" src="image.aspx?assetid=' + newsArray[15] + '&amp;blobType=blob_thumbnail_small" width="140" height="93" border="0" onmouseover="overEffect(this);" style="display:block;" /></td><td width="3" background="/pages/images/taAssets/vdrop-20x1024.jpg"></td></tr><tr><td width="0"></td><td height="4" background="/pages/images/taAssets/hdrop-1024x20.jpg"></td><td height="4" background="/pages/images/taAssets/cdrop-20x20.jpg"></td></tr></table><span style="position:relative;top:-2px;line-height:13px;" onmouseover="under(this,1)" onmouseout="under(this,0)">' + newsArray[16] + '</span>';
    $('news5').innerHTML = '<div style="position:relative;left:-5px;"><span class="newstxt">More News</span></div><div style="position:relative;left:-5px;"><img src="images/taAssets/arrow_grey2.gif" class="arrowgrey"><a class="normal" href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[24] + '">' + newsArray[21] + '</a></div>';
    $('news6').innerHTML = '<div style="position:relative;left:-5px;"><img src="images/taAssets/arrow_grey2.gif" class="arrowgrey"><a class="normal" href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[29] + '">' + newsArray[26] + '</a></div>';
    $('news7').innerHTML = '<div style="position:relative;left:-5px;"><img src="images/taAssets/arrow_grey2.gif" class="arrowgrey"><a class="normal" href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[34] + '">' + newsArray[31] + '</a></div>';

    showNews(0);
    $('news1').style.color = '#224c9e';

    if (exec == 0) {
        //Periodical Execution
        pe = new PeriodicalExecuter(showLarge, time);
        exec++;

        //Add Listener to the news buttons
        YAHOO.util.Event.addListener(ids, "click", fnCallback);

    }
}

//Error reading the XML file
function failureHandler(o) {
    //alert(o.status + " " + o.statusText);
}

//NEWS - Large article display control
function fnCallback(e) {
    change(this.id);
    pe.stop();
}

function change(element) {
    var divnimg = $('ajnewsimg');
    divnimg.style.display = 'none';
    clearbt();
    $(element).style.color = '#224c9e';
    showNews(indexArray[ids.indexOf(element)]);
    appear = new Effect.Appear(divnimg, { duration: 0.4 });
    x = ids.indexOf(element);
}

//Return to the original colour for all news buttons
function clearbt() {
    $('news1').style.color = '#999999';
    $('news2').style.color = '#999999';
    $('news3').style.color = '#999999';
    $('news4').style.color = '#999999';
}

//Displays the large article
function showNews(i) {
    //$('ajnewsimg').innerHTML = '<a href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[i+4] + '" class="newslargelink"><img alt="' + newsArray[i+1] + '" src="image.aspx?assetid=' + newsArray[i] + '&amp;blobType=blob_thumbnail_large" width="301" height="216" border="0" /><br />';
    $('ajnewsimg').innerHTML = '<table cellpadding="0" cellspacing="0" border="0" valign="top"><tr><td width="0" background="lside-10x1024.jpg"></td><td><a href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[i + 4] + '" class="newslargelink"><img alt="' + newsArray[i + 1] + '" src="image.aspx?assetid=' + newsArray[i] + '&amp;blobType=blob_thumbnail_large" width="301" height="216" border="0" /></td><td width="3" background="/pages/images/taAssets/vdrop-20x1024.jpg"></td></tr><tr><td width="0"></td><td height="4" background="/pages/images/taAssets/hdrop-1024x20.jpg"></td><td height="4" background="/pages/images/taAssets/cdrop-20x20.jpg"></td></tr></table><br />';
    $('ajnewstitle').innerHTML = '<a href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[i + 4] + '" class="newslargelink">' + newsArray[i + 1] + '</a>';
    var month = newsArray[i + 2].substring(5, 7);
    month = getMonthName(month);
    var day = newsArray[i + 2].substring(8, 10);
    var year = newsArray[i + 2].substring(0, 4);
    var newDate = day + " " + month + " " + year;


    $('ajnewsdate').innerHTML = newDate;
    $('ajnewstxt').innerHTML = newsArray[i + 3] + ' <a class="normal" href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsArray[i + 4] + '">Read more</a>';
}

function under(obj, sts) {
    if (sts == 1) { obj.style.textDecoration = 'underline'; }
    else { obj.style.textDecoration = 'none'; }
}

function showLarge() {
    x = x + 1;
    if (x > 3) {
        x = 0;
    }
    change(ids[x]);
}



//PHOTOS - AJAX COMPONENT
/////////////////////////////////////////////////////////////////////////////

width = new Array();
widthpop = new Array();

var cont = 0;
var contpop = 0;
var totalwidth = 0;

//Initialize with "latest" option. Tabs: "latest","galleries","popular"
function initPhotos() {

    var sUrl = 'AjaxPhotosXML.aspx?id=4&PageId=122&HandlerId=300';
    //alert("PhotosURL:" + sUrl);
    YAHOO.util.Connect.initHeader("Content-Type", "application/xml");
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: loadPhotos, failure: failureHandler }, null);

}

//displays or not the left and right arrows 
function checkCont(t) {
    if (t == "L") {
        totalwidth = 0;
        if (cont == 0) {
            $('butleft').style.display = 'none';
        }
        else {
            $('butleft').style.display = 'inline';
        }
        for (i = cont; i < width.length; i++) {
            totalwidth = totalwidth + width[i];
        }
        if (totalwidth < 500) {
            $('butright').style.display = 'none';
        }
        else {
            $('butright').style.display = 'inline';
        }
    }
    else if (t == "P") {
        totalwidth = 0;
        if (contpop == 0) {
            $('butleft').style.display = 'none';
        }
        else {
            $('butleft').style.display = 'inline';
        }
        for (i = contpop; i < widthpop.length; i++) {
            totalwidth = totalwidth + widthpop[i];
        }
        if (totalwidth < 500) {
            $('butright').style.display = 'none';
        }
        else {
            $('butright').style.display = 'inline';
        }
    }
}

//PHOTOS - Slide effect
function slideleft() {
    if ($('tabphoto').style.display == 'block') {
        var movel = (width[cont - 1] + 33);
        cont--;
        l = new Effect.Move($('tabphoto'), { x: movel, y: 0, mode: 'relative' });
        checkCont("L");
    }
    else if ($('tabpopphoto').style.display == 'block') {
        var movel = (widthpop[contpop - 1] + 33);
        contpop--;
        l = new Effect.Move($('tabpopphoto'), { x: movel, y: 0, mode: 'relative' });
        checkCont("P");
    }
}

//PHOTOS - Slide effect
function slideright() {
    if ($('tabphoto').style.display == 'block') {
        var mover = ((width[cont] + 33) * -1);
        cont++;
        r = new Effect.Move($('tabphoto'), { x: mover, y: 0, mode: 'relative' });
        checkCont("L");
    }
    else if ($('tabpopphoto').style.display == 'block') {
        var mover = ((widthpop[contpop] + 33) * -1);
        contpop++;
        r = new Effect.Move($('tabpopphoto'), { x: mover, y: 0, mode: 'relative' });
        checkCont("P");
    }
}

//PHOTOS
//onMouseOver fade effect - script.aculo.us library
function overEffect(element) {
    if ($(element))
        new Effect.Opacity(element, { duration: 0.5, transition: Effect.Transitions.linear, from: 0.5, to: 1.0 });
}

function loadPhotos(o) {
    strPhotos = '<table border="0" cellpadding="0" cellspacing="0" height="140"><tr>';
    strPopularPhotos = '<table border="0" cellpadding="0" cellspacing="0" height="140"><tr>';

    var xmlObj = o.responseXML.documentElement;
    var lines = xmlObj.getElementsByTagName('Latest_Photos').length;
    var linespop = xmlObj.getElementsByTagName('Popular_Photos').length;
    //alert(linespop);
    var vw = 140;
    var vh = 93;

    for (var i = 0; i < lines; i++) {
        //Portrait: width:93 height:140 / Landscape: width:140 height:93
        /* Removed: Always use a Portrait version.
        if (xmlObj.getElementsByTagName('Photos').item(i).getAttribute("isPortrait") == 1)
        {
        vw = 93;
        vh = 140;
        }
        else
        {
        vw = 140;
        vh = 93;
        }
        */
        //strPhotos = strPhotos + '<td><div id="photo' + (i+1) + '" onmouseover="overEffect(this);"><img alt="" src="image.aspx?assetid=' + xmlObj.getElementsByTagName('Photos').item(i).getAttribute("assetId") + '&amp;blobType=blob_thumbnail_small" width="' + vw + '" height="' + vh + '" border="0" /></div></td>';
        strPhotos = strPhotos + '<td><table cellpadding="0" cellspacing="0" border="0" valign="top" width="142"><tr><td width="0" background="lside-10x1024.jpg"></td><td><div id="photo' + (i + 1) + '" onmouseover="overEffect(this);"><a href="PhotosGallery.aspx?id=4&pageId=11500&HandlerId=2&archive=false&assetid=' + xmlObj.getElementsByTagName('Latest_Photos').item(i).getAttribute("order") + '&real_assetid=' + xmlObj.getElementsByTagName('Latest_Photos').item(i).getAttribute("assetId") + '&gallery=' + xmlObj.getElementsByTagName('Latest_Photos').item(i).getAttribute("photoid") + '"><img alt="' + xmlObj.getElementsByTagName('Latest_Photos').item(i).getAttribute("label") + '" src="image.aspx?assetid=' + xmlObj.getElementsByTagName('Latest_Photos').item(i).getAttribute("assetId") + '&amp;blobType=blob_thumbnail_small" width="' + vw + '" height="' + vh + '" border="0" /></a></div></td><td width="3" background="/pages/images/taAssets/vdrop-20x1024.jpg"></td></tr><tr><td width="0"></td><td height="4" background="/pages/images/taAssets/hdrop-1024x20.jpg"></td><td height="4" background="/pages/images/taAssets/cdrop-20x20.jpg"></td></tr></table></td>';
        if (i != (lines - 1)) {
            strPhotos = strPhotos + '<td><div id="divider1" style="display:block;width:5px;text-align:center;"><img alt="" src="images/taAssets/photos_divider.gif" width="1" height="88" border="0" /></div></td>';
        }
        width[i] = vw;

    }
    for (var p = 0; p < linespop; p++) {
        //strPopularPhotos = strPopularPhotos + '<td><div id="popphoto' + (i+1) + '" onmouseover="overEffect(this);"><img alt="" src="image.aspx?assetid=' + xmlObj.getElementsByTagName('Popular_Photos').item(p).getAttribute("assetId") + '&amp;blobType=blob_thumbnail_small" width="' + vw + '" height="' + vh + '" border="0" /></div></td>';
        strPopularPhotos = strPopularPhotos + '<td><table cellpadding="0" cellspacing="0" border="0" valign="top" width="142"><tr><td width="0" background="lside-10x1024.jpg"></td><td><div id="popphoto' + (i + 1) + '" onmouseover="overEffect(this);"><a href="PhotosGallery.aspx?id=4&pageId=11500&HandlerId=2&archive=false&assetid=' + xmlObj.getElementsByTagName('Popular_Photos').item(p).getAttribute("order") + '&gallery=' + xmlObj.getElementsByTagName('Popular_Photos').item(p).getAttribute("photoid") + '"><img alt="' + xmlObj.getElementsByTagName('Popular_Photos').item(p).getAttribute("label") + '" src="image.aspx?assetid=' + xmlObj.getElementsByTagName('Popular_Photos').item(p).getAttribute("assetId") + '&amp;blobType=blob_thumbnail_small" width="' + vw + '" height="' + vh + '" border="0" /></a></div></td><td width="3" background="/pages/images/taAssets/vdrop-20x1024.jpg"></td></tr><tr><td width="0"></td><td height="4" background="/pages/images/taAssets/hdrop-1024x20.jpg"></td><td height="4" background="/pages/images/taAssets/cdrop-20x20.jpg"></td></tr></table></td>';
        if (p != (linespop - 1)) {
            strPopularPhotos = strPopularPhotos + '<td><div id="divider1" style="display:block;width:5px;text-align:center;"><img alt="" src="images/taAssets/photos_divider.gif" width="1" height="88" border="0" /></div></td>';
        }
        widthpop[p] = vw;
    }

    strPhotos = strPhotos + '</tr></table>';
    strPopularPhotos = strPopularPhotos + '</tr></table>';
    $('tabphoto').innerHTML = strPhotos;
    $('tabpopphoto').innerHTML = strPopularPhotos;

    var firstTab = "latest";
    changeTabs(firstTab);

    YAHOO.util.Event.addListener("butleft", "click", slideleft);
    YAHOO.util.Event.addListener("butright", "click", slideright);
}

//TAB CONTROL - PHOTOS
//Write the html code for the tab menu. Add Listener to buttons.
function changeTabs(obj) {
    var divphotot = $('phototab');
    var divt1 = $('tabcell1');


    if (this.id == "latest" || obj == "latest") {
        //divphotot.innerHTML = '<table class="tabs" border="0" cellpadding="0" cellspacing="0" width="211" height="24"><tr><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td><td class="tabcells">Latest</td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td><td class="tabcell2"><div id="galleries">Galleries</div></td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider2.gif" width="1" height="24" border="0" /></td><td class="tabcell3"><div id="popular">Popular</div></td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider2.gif" width="1" height="24" border="0" /></td></tr></table>';
        divphotot.innerHTML = '<table class="tabs" border="0" cellpadding="0" cellspacing="0" width="141" height="24"><tr><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td><td class="tabcells">Latest</td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td><td class="tabcell2"><div id="popular">Popular</div></td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider2.gif" width="1" height="24" border="0" /></td></tr></table>';
        //var options = ["galleries","popular"];
        var options = ["popular"];
        YAHOO.util.Event.addListener(options, "click", changeTabs);
        //$('galleries').style.cursor = 'pointer';
        $('popular').style.cursor = 'pointer';
        checkCont("L");
        $('tabphoto').style.display = 'block';
    }
    /*
    if (this.id == "galleries"){
    divphotot.innerHTML = '<table class="tabs" border="0" cellpadding="0" cellspacing="0" width="211" height="24"><tr><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider2.gif" width="1" height="24" border="0" /></td><td class="tabcell1"><div id="latest">Latest</div></td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td><td class="tabcells">Galleries</td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td><td class="tabcell3"><div id="popular">Popular</div></td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider2.gif" width="1" height="24" border="0" /></td></tr></table>';
    var options = ["latest","popular"];
    YAHOO.util.Event.addListener(options, "click", changeTabs);
    $('latest').style.cursor = 'pointer';
    $('popular').style.cursor = 'pointer';
    $('tabphoto').style.display = 'none';
    $('butleft').style.display = 'none';
    $('butright').style.display = 'none';
    }
    */
    if (this.id == "popular") {
        //divphotot.innerHTML = '<table class="tabs" border="0" cellpadding="0" cellspacing="0" width="211" height="24"><tr><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider2.gif" width="1" height="24" border="0" /></td><td class="tabcell1"><div id="latest">Latest</div></td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider2.gif" width="1" height="24" border="0" /></td><td class="tabcell2"><div id="galleries">Galleries</div></td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td><td class="tabcells">Popular</td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td></tr></table>';
        divphotot.innerHTML = '<table class="tabs" border="0" cellpadding="0" cellspacing="0" width="141" height="24"><tr><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider2.gif" width="1" height="24" border="0" /></td><td class="tabcell1"><div id="latest">Latest</div></td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td><td class="tabcells">Popular</td><td class="tabdiv"><img alt="" src="images/taAssets/nav_divider3.gif" width="1" height="24" border="0" /></td></tr></table>';
        //var options = ["latest","galleries"];
        var options = ["latest"];
        YAHOO.util.Event.addListener(options, "click", changeTabs);
        $('latest').style.cursor = 'pointer';
        //$('galleries').style.cursor = 'pointer';
        $('tabphoto').style.display = 'none';
        $('butleft').style.display = 'none';
        $('butright').style.display = 'none';
        checkCont("P");
        $('tabpopphoto').style.display = 'block';
    }
}





//LATEST PHOTO GALLERY
/////////////////////////////////////////////////////////////////////////////
var strLatestPhotoGallery = new String();

var latestPhotoGalleryPage = 1;

function getLatestPhotoGalleryXML() {
    var sUrl = 'LatestPhotoGalleryXML.aspx?id=4&PageId=11500&HandlerId=300&PageNum=' + latestPhotoGalleryPage;
    //alert(sUrl);
    YAHOO.util.Connect.initHeader("Content-Type", "application/xml");
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: displayLatestPhotoGallery, failure: showError }, null);
}


//Success reading the XML file
function displayLatestPhotoGallery(o) {
    strLatestPhotoGallery = '<div class="moduleimg">';
    var divln = $("latestphotos");
    var xmlObj = o.responseXML.documentElement;
    var noimage = "RDM39059.6785644907";

    var title = xmlObj.getElementsByTagName('PhotoGallery').item(0).getAttribute("GalleryTitle");
    var shortBody = ""; //xmlObj.getElementsByTagName('PhotoGallery').item(0).getAttribute("ShortBody");
    var photoGalleryId = xmlObj.getElementsByTagName('PhotoGallery').item(0).getAttribute("PhotoGalleryID");

    /*
    if (title.length > 25)
    {
    title = title.substring(0,36);
    var lastwordtitle = title.lastIndexOf(" ");
    title = (title.substring(0,lastwordtitle) +  '...');
    }
    */

    if (shortBody.length > 71) {
        shortBody = shortBody.substring(0, 70);
        var lastword = shortBody.lastIndexOf(" ");
        shortBody = (shortBody.substring(0, lastword) + '...');
    }

    shortBody = shortBody + ' <a href="http://www.tennis.com.au/pages/PhotosGallery.aspx?id=4&pageId=11500&HandlerId=2&archive=false&AssetID=1&Gallery=' + photoGalleryId + '">more</a>';

    bodyImage = xmlObj.getElementsByTagName('PhotoGallery').item(0).getAttribute("AssetId01") + '&amp;blobType=blob_thumbnail_small';

    if ((bodyImage == "") || (bodyImage == " ") || (bodyImage == "null") || (bodyImage == "NULL") || (bodyImage.indexOf(".") == -1)) {
        bodyImage = noimage;
    }

    strLatestPhotoGallery = strLatestPhotoGallery + '<a href="http://www.tennis.com.au/pages/PhotosGallery.aspx?id=4&pageId=11500&HandlerId=2&archive=false&AssetID=1&Gallery=' + photoGalleryId + '"><img alt="' + title + '" src="image.aspx?assetid=' + bodyImage + '" width="140" height="93" border="0" onmouseover="overEffect(this);"></a></div><div class="modulecont">';

    strLatestPhotoGallery = strLatestPhotoGallery + '<span class="boldtxt"><a href="http://www.tennis.com.au/pages/PhotosGallery.aspx?id=4&pageId=11500&HandlerId=2&archive=false&AssetID=1&Gallery=' + photoGalleryId + '" class="box">' + title + '</a></span>' + shortBody + '</div>';


    if (latestPhotoGalleryPage == 1) {
        strLatestPhotoGallery = strLatestPhotoGallery + '<div class="modulelinksmore" id="latestnewsnav"><div style="position:relative;top:0px;left:235px;text-align:left;">';
        strLatestPhotoGallery = strLatestPhotoGallery + '<a href="Javascript:nextPhotoGallery();" class="simple">Next<img alt="" src="images/taAssets/arrow_grey4.gif" border="0" /></a></div></div>';
    }
    else {
        if (latestPhotoGalleryPage < 7) {
            strLatestPhotoGallery = strLatestPhotoGallery + '<div class="modulelinksmore" id="latestnewsnav"><div style="position:relative;top:0px;left:158px;text-align:left;">';
            strLatestPhotoGallery = strLatestPhotoGallery + '<a href="Javascript:prevPhotoGallery();" class="simple"><img alt="" src="images/taAssets/arrow_grey3.gif" border="0" />Previous</a><span style="color:#d6d6d6;">|</span>';
            strLatestPhotoGallery = strLatestPhotoGallery + '<a href="Javascript:nextPhotoGallery();" class="simple">Next<img alt="" src="images/taAssets/arrow_grey4.gif" border="0" /></a></div></div>';
        }
        else {
            strLatestPhotoGallery = strLatestPhotoGallery + '<div class="modulelinksmore" id="latestnewsnav"><div style="position:relative;top:0px;left:158px;text-align:left;">';
            strLatestPhotoGallery = strLatestPhotoGallery + '<a href="Javascript:prevPhotoGallery();" class="simple"><img alt="" src="images/taAssets/arrow_grey3.gif" border="0" />Previous</a>';
        }
    }

    //alert(strLatestPhotoGallery);
    divln.innerHTML = strLatestPhotoGallery;
}

function nextPhotoGallery() {
    latestPhotoGalleryPage++;
    getLatestPhotoGalleryXML();
}

function prevPhotoGallery() {
    latestPhotoGalleryPage--;
    getLatestPhotoGalleryXML();
}




//PARTNERS
/////////////////////////////////////////////////////////////////////////////
//Displays the partner logo.
var logoindex = 0;
strLogos = new String();

function initPartners() {
    var sUrl = 'AjaxPartnersXML.aspx?id=4&PageId=122&HandlerId=300';
    YAHOO.util.Connect.initHeader("Content-Type", "application/xml");
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: loadPartners, failure: failureHandler }, null);
}

function loadPartners(o) {
    var xmlObj = o.responseXML.documentElement;
    var lineslogos = xmlObj.getElementsByTagName('Logos').length;

    for (var l = 0; l < lineslogos; l++) {
        logoimg[l] = xmlObj.getElementsByTagName('Logos').item(l).getAttribute("Logo");
        logourl[l] = xmlObj.getElementsByTagName('Logos').item(l).getAttribute("URL");
        logoname[l] = xmlObj.getElementsByTagName('Logos').item(l).getAttribute("Name");
    }

    //Periodical Execution
    showLogo();
    var lg = new PeriodicalExecuter(showLogo, "10");
}

function showLogo() {
    changeLogo(logoindex);
    logoindex++;
    if (logoindex > (logoname.length - 1)) {
        logoindex = 0;
    }
}

function changeLogo(e) {
    var divpartner = $('partner');
    //strLogos = '<a href="http://' + logourl[e] + '"><img alt="' + logoname[e] + '" src="image.aspx?assetid=' + logoimg[e] + '" border="0" /></a>';
    strLogos = '<a href="http://' + logourl[e] + '"><img alt="' + logoname[e] + '" src="image.aspx?assetid=' + logoimg[e] + '" border="0" /></a>';
    divpartner.innerHTML = "";
    divpartner.style.display = 'none';
    divpartner.innerHTML = strLogos;
    appear = new Effect.Appear(divpartner, { duration: 0.4 });
}






//MESSAGES
/////////////////////////////////////////////////////////////////////////////
//Displays the message for Messaging System.
function getInboxMessage() {
    var sUrl = 'AjaxInboxMessageXML.aspx?id=4&PageId=122&HandlerId=300';
    YAHOO.util.Connect.initHeader("Content-Type", "application/xml");
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: loadInboxMessage, failure: failureHandler }, null);
}

function loadInboxMessage(o) {
    var strMsg = "You have no messages.";
    var xmlObj = o.responseXML.documentElement;

    var newTotal = parseInt(xmlObj.getElementsByTagName('Session').item(0).getAttribute("NewTotal"));
    var oldTotal = parseInt(xmlObj.getElementsByTagName('Session').item(0).getAttribute("OldTotal"));

    if (!(newTotal == 0 && oldTotal == 0)) {
        if (newTotal == 0)
            strMsg = 'You have no new messages.';
        else if (newTotal == 1)
            strMsg = 'You have 1 new message to view.';
        else if (newTotal > 1)
            strMsg = 'You have ' + newTotal.toString() + ' new messages to view.';
    }
    if (document.getElementById('spInboxMsg'))
        document.getElementById('spInboxMsg').innerHTML = strMsg;
}









//LATEST NEWS AND MORE NEWS
/////////////////////////////////////////////////////////////////////////////
strLatest = new String();

var latestNewsPage = 1;

moreimg = new Array();
moretitle = new Array();
moretxt = new Array();
moreurl = new Array();

function getLatestNewsXML() {
    var sUrl = 'LatestNewsXML.aspx?id=4&PageId=122&HandlerId=300&PageNum=' + latestNewsPage;
    //alert(sUrl);
    YAHOO.util.Connect.initHeader("Content-Type", "application/xml");
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: displayLatestNews, failure: showError }, null);
}

function getMoreNewsXML() {
    var sUrl = 'AjaxMoreNewsXML.aspx?id=4&PageId=122&HandlerId=300';
    //alert(sUrl);
    YAHOO.util.Connect.initHeader("Content-Type", "application/xml");
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: displayMoreNews, failure: showError }, null);
}


//Success reading the XML file
function displayLatestNews(o) {
    strLatest = '<div class="moduleimg">';
    var divln = $("latestnews");
    var xmlObj = o.responseXML.documentElement;
    var noimage = "RDM39059.6785644907";

    var title = xmlObj.getElementsByTagName('News').item(0).getAttribute("Title");
    var shortBody = xmlObj.getElementsByTagName('News').item(0).getAttribute("ShortBody");
    var newsId = xmlObj.getElementsByTagName('News').item(0).getAttribute("NewsID");

    /*
    if (title.length > 25)
    {
    title = title.substring(0,36);
    var lastwordtitle = title.lastIndexOf(" ");
    title = (title.substring(0,lastwordtitle) +  '...');
    }
    */

    if (shortBody.length > 71) {
        shortBody = shortBody.substring(0, 70);
        var lastword = shortBody.lastIndexOf(" ");
        shortBody = (shortBody.substring(0, lastword) + '...');
    }

    shortBody = shortBody + ' <a href="http://www.tennis.com.au/pages/News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsId + '">more</a>';

    bodyImage = xmlObj.getElementsByTagName('News').item(0).getAttribute("BodyImage") + '&amp;blobType=blob_thumbnail_small';

    if ((bodyImage == "") || (bodyImage == " ") || (bodyImage == "null") || (bodyImage == "NULL") || (bodyImage.indexOf(".") == -1)) {
        bodyImage = noimage;
    }

    strLatest = strLatest + '<table cellpadding="0" cellspacing="0" border="0" valign="top"><tr><td width="0" background="lside-10x1024.jpg"></td><td>';

    //strLatest = strLatest + '<a href="http://tennis.am.local/pages/News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsId + '"><img alt="' + title + '" src="image.aspx?assetid=' + bodyImage + '" width="140" height="93" border="0" onmouseover="overEffect(this);"></a></div><div class="modulecont">';
    strLatest = strLatest + '<a href="http://www.tennis.com.au/pages/News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsId + '"><img alt="' + title + '" src="image.aspx?assetid=' + bodyImage + '" width="140" height="93" border="0" onmouseover="overEffect(this);"></a></td><td width="3" background="/pages/images/taAssets/vdrop-20x1024.jpg"></td></tr><tr><td width="0"></td><td height="4" background="/pages/images/taAssets/hdrop-1024x20.jpg"></td><td height="4" background="/pages/images/taAssets/cdrop-20x20.jpg"></td></tr></table></div><div class="modulecont">';

    strLatest = strLatest + '<span class="boldtxt"><a href="http://www.tennis.com.au/pages/News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + newsId + '" class="box">' + title + '</a></span>' + shortBody + '</div>';


    if (latestNewsPage == 1) {
        strLatest = strLatest + '<div class="modulelinksmore" id="latestnewsnav"><div style="position:relative;top:-3px;left:235px;text-align:left;">';
        strLatest = strLatest + '<a href="Javascript:nextNews();" class="simple">Next<img alt="" src="images/taAssets/arrow_grey4.gif" border="0" /></a></div></div>';
    }
    else {
        if (latestNewsPage < 7) {
            strLatest = strLatest + '<div class="modulelinksmore" id="latestnewsnav"><div style="position:relative;top:-3px;left:158px;text-align:left;">';
            strLatest = strLatest + '<a href="Javascript:prevNews();" class="simple"><img alt="" src="images/taAssets/arrow_grey3.gif" border="0" />Previous</a><span style="color:#d6d6d6;">|</span>';
            strLatest = strLatest + '<a href="Javascript:nextNews();" class="simple">Next<img alt="" src="images/taAssets/arrow_grey4.gif" border="0" /></a></div></div>';
        }
        else {
            strLatest = strLatest + '<div class="modulelinksmore" id="latestnewsnav"><div style="position:relative;top:-3px;left:158px;text-align:left;">';
            strLatest = strLatest + '<a href="Javascript:prevNews();" class="simple"><img alt="" src="images/taAssets/arrow_grey3.gif" border="0" />Previous</a>';
        }
    }

    //alert(strLatest);
    divln.innerHTML = strLatest;
}

function nextNews() {
    latestNewsPage++;
    getLatestNewsXML();
}

function prevNews() {
    latestNewsPage--;
    getLatestNewsXML();
}


//MORE NEWS
function displayMoreNews(o) {
    var xmlObj = o.responseXML.documentElement;
    var lines = xmlObj.getElementsByTagName('News').length;

    for (var i = 0; i < lines; i++) {
        moreimg[i] = xmlObj.getElementsByTagName('News').item(i).getAttribute("BodyImage");
        moretitle[i] = xmlObj.getElementsByTagName('News').item(i).getAttribute("Title");
        moretxt[i] = xmlObj.getElementsByTagName('News').item(i).getAttribute("ShortBody");
        moreurl[i] = xmlObj.getElementsByTagName('News').item(i).getAttribute("NewsID");
    }

    //First News
    changeMoreNews(0);
}

function changeMoreNews(e) {
    var divmoreimg = $("morenewsimg");
    var divmoretxt = $("morenewstxt");
    var divmorelks = $("morenewslinks");

    var txt = (moretxt[e].length > 65) ? (moretxt[e].substring(0, 64) + '...') : moretxt[e];
    txt = txt + ' <a href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + moreurl[e] + '">more</a>';

    strMoreNews = new String();
    strMoreLks = new String();

    strMoreNews = '<span class="boldtxt">' + moretitle[e] + '</span>' + txt;

    for (var i = 0; i < moretitle.length; i++) {
        if (i != e) {
            strMoreLks = strMoreLks + '<span class="modulelink"><img alt="" src="images/taAssets/arrow_grey2.gif" class="arrowgrey" /><a href="News.aspx?id=4&pageId=11478&HandlerId=2&archive=false&newsid=' + moreurl[i] + '" class="normal">' + moretitle[i] + '</a></span>';
        }
    }

    divmoreimg.innerHTML = '<img src="image.aspx?assetid=' + moreimg[e] + '&amp;blobType=blob_thumbnail_small" />';
    divmoretxt.innerHTML = strMoreNews;
    divmorelks.innerHTML = strMoreLks;
    checkNav(e);
}

function checkNav(e) {
    var divprev = $("morenewsprev");
    var divnext = $("morenewsnext");

    if (e == 0) {
        divprev.innerHTML = '';
        divnext.innerHTML = '<a href="Javascript:changeMoreNews(' + (e + 1) + ');" class="simple">Next<img alt="" src="images/taAssets/arrow_grey4.gif" border="0" /></a>';
    }
    else if (e == (moretitle.length - 1)) {
        divprev.innerHTML = '<a href="Javascript:changeMoreNews(' + (e - 1) + ');" class="simple"><img alt="" src="images/taAssets/arrow_grey3.gif" border="0" />Previous</a><span style="color:#d6d6d6;">|</span>';
        divnext.innerHTML = '';
    }
    else {
        divprev.innerHTML = '<a href="Javascript:changeMoreNews(' + (e - 1) + ');" class="simple"><img alt="" src="images/taAssets/arrow_grey3.gif" border="0" />Previous</a><span style="color:#d6d6d6;">|</span>';
        divnext.innerHTML = '<a href="Javascript:changeMoreNews(' + (e + 1) + ');" class="simple">Next<img alt="" src="images/taAssets/arrow_grey4.gif" border="0" /></a>';
    }
}


//Error reading the XML file
function showError(o) {
    //alert(o.status + " " + o.statusText);
}



//CALENDAR
/////////////////////////////////////////////////////////////////////////////
var pageNum = 1;
var tour = "";
var state = "";
var startDate = "";
var endDate = "";
var type = "";
var times = 1;
var effDate = "";

var currentMonth;

function calendarGetUniqueQueryStringValue()
{
	var date= new Date();
	return date.getTime();
}

function getCalendarXML(n, t) {
    if ($("divtour").value != tour) {
        tour = $("divtour").value;
        n = 1;
    }

    if ($("SelectState").options[$("SelectState").selectedIndex].value != state) {
        state = $("SelectState").options[$("SelectState").selectedIndex].value;
        n = 1;
    }

    var currentDate = new Date();

    effDate = currentDate.getFullYear().toString();

    currentMonth = (currentDate.getMonth() + 1);

    //alert(currentDate + " - " + currentDate.getMonth());

    if (currentMonth.toString().length == 1) {
        effDate = effDate + "-0" + (currentDate.getMonth() + 1).toString();
    }
    else {
        effDate = effDate + "-" + (currentDate.getMonth() + 1).toString();
    }

    if (currentDate.getDate().toString().length == 1) {
        effDate = effDate + "-0" + currentDate.getDate().toString();
    }
    else {
        effDate = effDate + "-" + currentDate.getDate().toString();
    }

    effDate = effDate + "T00:00:00";

	//effDate= '1 jan 2020';
	startDate= effDate;

    if (times == 1) {
        /*var startDate = "'" + effDate + "'";
        //alert(startDate);
        var endDate = "'2106-01-01T00:00:00'";
        var type = "NULL";*/
        //startDate = endDate = effDate;
    }
    else {
/*	
        if ($("SelectStart").options[$("SelectStart").selectedIndex].value != startDate) {
            startDate = $("SelectStart").options[$("SelectStart").selectedIndex].value;
            n = 1;
        }
*/		
/*		
        if ($("SelectEnd").options[$("SelectEnd").selectedIndex].value != endDate) {
            endDate = $("SelectEnd").options[$("SelectEnd").selectedIndex].value;
            n = 1;
        }
*/		
        if ($("SelectType").options[$("SelectType").selectedIndex].value != type) {
            type = $("SelectType").options[$("SelectType").selectedIndex].value;
            n = 1;
        }
    }
    /*if (startDate == "NULL")
    {
    startDate = "NULL";
    }
    if (endDate == "NULL")
    {
    endDate = "NULL";
    }
    if (type == "NULL")
    {
    type = "NULL";
    }
	
	if (state == "ALL")
    {
    state = "NULL";
    }*/

    pageNum = n;
    //var sUrl = 'CalendarXML.aspx?id=4&PageId=226&HandlerId=300&Tour=' + tour + '&State=' + state + '&SDate=' + startDate + '&EDate=' + endDate + '&Type=' + type + '&PageNum=' + pageNum;
    var sUrl = 'CalendarXML.aspx?id=4&PageId=226&HandlerId=300&Tour=' + encodeURIComponent(tour) + '&SDate=' + startDate + '&State=' + encodeURIComponent(state) + '&Type=' + encodeURIComponent(type) + '&PageNum=' + pageNum + '&unique=' + calendarGetUniqueQueryStringValue();
    //alert(sUrl);
    YAHOO.util.Connect.initHeader("Content-Type", "application/xml");
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: loadCalendar, failure: failureHandler }, null);
}

function nextPage() {
    pageNum++;
    getCalendarXML(pageNum, 1);
}

function prevPage() {
    pageNum--;
    getCalendarXML(pageNum, 1);
}

function calendarFormatDate(datevalue)
{
	if (datevalue.length<11)
		return "";
		
	return datevalue.substring(8, 10) + ' ' + getMonthName(datevalue.substring(5, 7));
}

//Success reading the XML file
function loadCalendar(o) {
    var divr = $("ajaxres");
    var dprev = $("divprev");
    var dnext = $("divnext");
    var dprevtop = $("divprevtop");
    var dnexttop = $("divnexttop");
    var dstart = $("start");
    var dend = $("end");
    var dtype = $("type");

    var xmlObj = o.responseXML.documentElement;
    //alert(o.responseText);
    var lines = xmlObj.getElementsByTagName('Calendar').length;
    var slines = xmlObj.getElementsByTagName('StartDate').length;
    var elines = xmlObj.getElementsByTagName('EndDate').length;
    var tlines = xmlObj.getElementsByTagName('Type').length;
    var stlines = xmlObj.getElementsByTagName('States').length;

    //alert(lines + " " + slines + " " + elines + " " + tlines + " " + stlines);
    var strResults = '<table border="0" cellpadding="3" cellspacing="0" width="615">'

    if (lines == null || lines == 0) {
        strResults += '<tr><td class="tablinew">No tournaments found with the selected details.</td></tr>';
    }
    else {
        strResults += '<tr><td width="75" class="tabhead">Starts</td><td width="165" class="tabhead">Tournament</td><td width="150" class="tabhead">Venue</td><td width="50" class="tabhead">State</td><td width="50" class="tabhead">Surface</td><td width="50" class="tabhead">Type</td><td width="75" class="tabhead">Entry Deadline</td></tr>';

        var sDate = "";
        var eDate = "";
        var tour = "";
        var venue = "";
        var State = "";
        var tType = "";
        var ar = 0;
        var ardesc = "";
		var surface= "";
		var entrydeadline= "";

        styles = new Array("tablineg", "tablinew");
        var index = 0;

        var totalPages = 1;
        var pageNumber = 1;
        var pagelink = "";
        var externallink = "";


        for (var i = 0; i < lines; i++) {
            totalPages = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("TotalPages");
            pageNumber = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("PageNumber");

            sDate = calendarFormatDate(xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("StartDate"));
            eDate = calendarFormatDate(xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("EndDate"));
            //sDate = xmlObj.childNodes(1).getAttribute("StartDate").substring(8,10) + ' ' + getMonthName(xmlObj.childNodes(1).getAttribute("StartDate").substring(5,7));
            //eDate = xmlObj.childNodes(i).getAttribute("EndDate").substring(8,10) + ' ' + getMonthName(xmlObj.childNodes(i).getAttribute("EndDate").substring(5,7));
            tour = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("Tournament");
            venue = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("Venue");
            State = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("StateName");
            surface = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("Surface");
            entrydeadline = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("EntryDeadline");
            pagelink = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("InternalURL");
            externallink = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("ExternalURL");

            if (xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("AR") == 0)
                ardesc = "No";
            else
                ardesc = "Yes";

            /*if (State == null)
            {
            State = "";
            }*/
            tType = xmlObj.getElementsByTagName('Calendar').item(i).getAttribute("Type");
            //strResults = strResults + '<tr><td width="110" class="' + styles[index] + '">' + sDate + '</td><td width="110" class="' + styles[index] + '">' + eDate + '</td><td width="130" class="' + styles[index] + '"><a href="' + pagelink + '">' + tour + '</a></td><td width="70" class="' + styles[index] + '">' + venue + '</td><td width="70" class="' + styles[index] + '">' + State + '</td><td width="125" class="' + styles[index] + '" colspan="2">' + tType + '</td></tr>';
            //strResults = strResults + '<tr><td width="80" class="' + styles[index] + '">' + sDate + '</td><td width="80" class="' + styles[index] + '">' + eDate + '</td><td width="150" class="' + styles[index] + '"><a href="' + pagelink + '">' + tour + '</a></td><td width="110" class="' + styles[index] + '">' + venue + '</td><td width="70" class="' + styles[index] + '">' + State + '</td><td width="100" class="' + styles[index] + '">' + tType + '</td><td width="25" class="">ar</td></tr>';
            if (pagelink != '')
                strResults = strResults + '<tr><td class="' + styles[index] + '">' + sDate + '</td><td class="' + styles[index] + '"><a href="' + pagelink + '">' + tour + '</a></td><td class="' + styles[index] + '">' + venue + '</td><td class="' + styles[index] + '">' + State + '</td><td class="' + styles[index] + '">' + surface + '</td><td class="' + styles[index] + '">' + tType + '</td><td class="' + styles[index] + '">' + entrydeadline + '</td></tr>';
            else if (externallink != '')
                strResults = strResults + '<tr><td class="' + styles[index] + '">' + sDate + '</td><td class="' + styles[index] + '"><a href="javascript:viewTournamentLink(\'' + externallink + '\');">' + tour + '</a></td><td class="' + styles[index] + '">' + venue + '</td><td class="' + styles[index] + '">' + State + '</td><td class="' + styles[index] + '">' + surface + '</td><td class="' + styles[index] + '">' + tType + '</td><td class="' + styles[index] + '">' + entrydeadline + '</td></tr>';
            else
                strResults = strResults + '<tr><td class="' + styles[index] + '">' + sDate + '</td><td class="' + styles[index] + '">' + tour + '</td><td class="' + styles[index] + '">' + venue + '</td><td class="' + styles[index] + '">' + State + '</td><td class="' + styles[index] + '">' + surface + '</td><td class="' + styles[index] + '">' + tType + '</td><td class="' + styles[index] + '">' + entrydeadline + '</td></tr>';
            index++;
            if (index == 2) {
                index = 0;
            }
        }
    }

    if (times == 1) {
        var strDrop = new String();
        var option = new String();
		
		/*
        strDrop = '<select ID="SelectStart" NAME="SelectStart" class="fieldcal"><option value="" selected="true">All</option>';
        for (var s = 0; s < slines; s++) {
            option = xmlObj.getElementsByTagName('StartDate').item(s).getAttribute("StartDate");
            //strDrop = strDrop + '<option value="' + option + '">' + option.substring(8,10) + ' ' + getMonthName(option.substring(5,7)) + '</option>';
            //alert(option + " " + startDate);

            if (option.substring(0, 7) == effDate.substring(0, 7))
                strDrop = strDrop + '<option value="' + option + '" selected>' + getMonthAbbr(option.substring(5, 7)) + ' - ' + option.substring(2, 4) + '</option>';
            else
                strDrop = strDrop + '<option value="' + option + '">' + getMonthAbbr(option.substring(5, 7)) + ' - ' + option.substring(2, 4) + '</option>';
        }
        strDrop = strDrop + '</select>';
        //alert(strDrop);
        dstart.innerHTML = strDrop;
		*/

/*		
        strDrop = '<select ID="SelectEnd" NAME="SelectEnd" class="fieldcal"><option value="" selected="true">All</option>';
        for (var e = 0; e < elines; e++) {
            option = xmlObj.getElementsByTagName('EndDate').item(e).getAttribute("EndDate");
            //strDrop = strDrop + '<option value="' + option + '">' + option.substring(8,10) + ' ' + getMonthName(option.substring(5,7)) + '</option>';
            //	strDrop = strDrop + '<option value="' + option + '">' + getMonthAbbr(option.substring(5,7)) + ' - ' + option.substring(2,4) + '</option>';

            if (option.substring(0, 7) == effDate.substring(0, 7))
                strDrop = strDrop + '<option value="' + option + '" selected>' + getMonthAbbr(option.substring(5, 7)) + ' - ' + option.substring(2, 4) + '</option>';
            else
                strDrop = strDrop + '<option value="' + option + '">' + getMonthAbbr(option.substring(5, 7)) + ' - ' + option.substring(2, 4) + '</option>';
        }
        strDrop = strDrop + '</select>';
        //alert(strDrop);
        dend.innerHTML = strDrop;
*/
		
        strDrop = '<select ID="SelectType" NAME="SelectType" class="fieldcal"><option value="" selected="true">All</option>';
        for (var t = 0; t < tlines; t++) {
            option = xmlObj.getElementsByTagName('Type').item(t).getAttribute("TournamentType");
            strDrop = strDrop + '<option value="' + xmlObj.getElementsByTagName('Type').item(t).getAttribute("TypeID") + '">' + option + '</option>';
        }
        strDrop = strDrop + '</select>';
        //alert(strDrop);
        dtype.innerHTML = strDrop;

        times++;
    }


    strResults = strResults + '</table>';
    //alert(strResults);
    divr.innerHTML = strResults;

    /*if (totalPages > 1)
    {
    if (pageNumber < totalPages)
    {
    dnext.innerHTML = '<a href="Javascript:nextPage();" class="pages">next &gt;</a>';
    dnexttop.innerHTML = '<a href="Javascript:nextPage();" class="pages">next &gt;</a>';
    }
    else
    {
    dnext.innerHTML = '';
    dnexttop.innerHTML = '';
    }
    }*/
    if (parseInt(totalPages) > parseInt(pageNumber)) {
        dnext.innerHTML = '<a href="Javascript:nextPage();" class="pages">next &gt;</a>';
        dnexttop.innerHTML = '<a href="Javascript:nextPage();" class="pages">next &gt;</a>';
    }
    else {
        dnext.innerHTML = '';
        dnexttop.innerHTML = '';
    }
    if (pageNumber > 1) {
        dprev.innerHTML = '<a href="Javascript:prevPage();" class="pages">&lt; previous</a>';
        dprevtop.innerHTML = '<a href="Javascript:prevPage();" class="pages">&lt; previous</a>';
    }
    else {
        dprev.innerHTML = '';
        dprevtop.innerHTML = '';
    }
}

function getMonthName(e) {
    var name = "";
    switch (e) {
        case "01":
            name = "January";
            break;
        case "02":
            name = "February";
            break;
        case "03":
            name = "March";
            break;
        case "04":
            name = "April";
            break;
        case "05":
            name = "May";
            break;
        case "06":
            name = "June";
            break;
        case "07":
            name = "July";
            break;
        case "08":
            name = "August";
            break;
        case "09":
            name = "September";
            break;
        case "10":
            name = "October";
            break;
        case "11":
            name = "November";
            break;
        case "12":
            name = "December";
            break;
        default:
            name = e;
    }
    return name;
}

function getMonthAbbr(e) {
    var name = "";
    switch (e) {
        case "01":
            name = "Jan";
            break;
        case "02":
            name = "Feb";
            break;
        case "03":
            name = "Mar";
            break;
        case "04":
            name = "Apr";
            break;
        case "05":
            name = "May";
            break;
        case "06":
            name = "Jun";
            break;
        case "07":
            name = "Jul";
            break;
        case "08":
            name = "Aug";
            break;
        case "09":
            name = "Sep";
            break;
        case "10":
            name = "Oct";
            break;
        case "11":
            name = "Nov";
            break;
        case "12":
            name = "Dec";
            break;
        default:
            name = " ";
    }
    return name;
}

//PRINT FUNCTION
/////////////////////////////////////////////////////////////////////////////
function printPage(SiteId, NewsID, PageId, Type) {
    //alert(SiteId + " - " + NewsID + " - " + PageId + " - " + Type);

    if (Type == "news") {
        var strUrl = 'News.aspx?id=' + SiteId + '&pageId=' + PageId + '&HandlerId=2&archive=false&newsid=' + NewsID + '&printPage=1';
        //alert(strUrl);
        var load = window.open(strUrl, '', 'scrollbars=Yes,menubar=no,height=800,width=670,resizable=no,toolbar=no,location=no,status=no');
    }

    if (Type == "article") {
        var strUrl = 'default.aspx?id=' + SiteId + '&pageId=' + PageId + '&printPage=1';
        var load = window.open(strUrl, '', 'scrollbars=Yes,menubar=no,height=800,width=670,resizable=no,toolbar=no,location=no,status=no');
    }
}

//Photo Gallery
/////////////////////////////////////////////////////////////////////////////
var galleryPos = 0;
var galleryTotal = 0;
var gallerySelType;

function initPhotoGallery() {
    galleryPos = parseInt($('gallery1').innerHTML);
    galleryTotal = parseInt($('gallery2').innerHTML);
    gallerySelType = $('gallery3').innerHTML;

    galleryShowSel();
}

function galleryShowSel() {

    strImg = new String();
    strTag = new String();
    strTag = '';

    if ($('o' + galleryPos).innerHTML == 1) {
        $('galleryP').style.display = 'block';
        $('galleryL').style.display = 'none';

        strImg = '<img alt="' + $('c' + galleryPos).innerHTML + '" src="image.aspx?assetid=' + $('p' + galleryPos).innerHTML + '&amp;blobType=portait" width="300" height="450" border="0"/>';
        $('galleryPImg').innerHTML = strImg;

        effects = overEffect($('galleryPImg'));

        $('galleryPCaption').innerHTML = $('c' + galleryPos).innerHTML;
        if ($('t' + galleryPos).innerHTML != '') {
            strTag = 'tags: ' + $('t' + galleryPos).innerHTML;
        }
        else {
            strTag = '';
        }
        $('galleryPTag').innerHTML = strTag;
        $('galleryPCredit').innerHTML = $('cr' + galleryPos).innerHTML;
    }
    else {
        $('galleryP').style.display = 'none';
        $('galleryL').style.display = 'block';

        strImg = '<img alt="' + $('c' + galleryPos).innerHTML + '" src="image.aspx?assetid=' + $('p' + galleryPos).innerHTML + '&amp;blobType=landscape" width="478" height="319" border="0"/>';
        $('galleryLImg').innerHTML = strImg;

        effects = overEffect($('galleryLImg'));

        $('galleryLCaption').innerHTML = $('c' + galleryPos).innerHTML;
        if ($('t' + galleryPos).innerHTML != '') {
            strTag = 'tags: ' + $('t' + galleryPos).innerHTML;
        }
        else {
            strTag = '';
        }
        $('galleryLTag').innerHTML = strTag;
        $('galleryLCredit').innerHTML = $('cr' + galleryPos).innerHTML;
    }

    updateNav();
}

function updateNav() {
    if (galleryPos > 1) {
        $('gprev').innerHTML = '<a href="javascript:galleryShowPrev(' + (galleryPos - 1) + ');" class="simple2">&lt; previous</a>';
    }
    else {
        $('gprev').innerHTML = '';
    }
    if (galleryPos < galleryTotal) {
        $('gnext').innerHTML = '<a href="javascript:galleryShowNext(' + (galleryPos + 1) + ');" class="simple2">next &gt;</a>';
    }
    else {
        $('gnext').innerHTML = '';
    }

    $('gpages').innerHTML = 'Photo ' + galleryPos + ' of ' + galleryTotal;
}

function galleryShowPrev(p) {
    galleryPos--;
    galleryShowSel()
}

function galleryShowNext(p) {
    galleryPos++;
    galleryShowSel()
}

function startSlideshow() {
    $('gprev').style.display = 'none';
    $('gnext').style.display = 'none';

    $('gcontrol').innerHTML = '<a href="javascript:stopSlideshow();" class="simple2">Stop Slideshow</a>';
    pe2 = new PeriodicalExecuter(nextSlide, 5);
}

function stopSlideshow() {
    $('gcontrol').innerHTML = '<a href="javascript:startSlideshow();" class="simple2">Start Slideshow</a>';
    pe2.stop();

    $('gprev').style.display = 'block';
    $('gnext').style.display = 'block';
}

function nextSlide() {
    if (galleryPos < galleryTotal) {
        galleryShowNext(galleryPos);
    }
    else {
        galleryPos = 0;
        galleryShowNext(galleryPos);
    }
}


//Audio Gallery
/////////////////////////////////////////////////////////////////////////////
function initAudioGallery() {
    if ($('firstAudio').innerHTML != '' && $('firstFile').innerHTML != '') {
        setvideo('/pages/images/AudioPlayer/Audio/' + $('firstAudio').innerHTML + '.mp3', $('firstLength').innerHTML, $('firstFile').innerHTML);
    }
}

//Video Gallery
/////////////////////////////////////////////////////////////////////////////
function initVideoGallery() {
    if ($('firstVideo').innerHTML != '' && $('firstVFile').innerHTML != '') {
        setvideo('/pages/images/VideoPlayer/clips/' + $('firstVideo').innerHTML + '.flv', $('firstVLength').innerHTML, $('firstVFile').innerHTML);
    }
}

//Map - Driving directions
/////////////////////////////////////////////////////////////////////////////
var startpt_streetNumber = "";
var startpt_streetName = "";
var startpt_suburb = "";
var startpt_state = "";
var startpt_postcode = "";
var clicked;
var previousClicked = "";

///////////////////////////////////////////////////////////////////////////////////////////////
// Versions 3, 4, and 5 used the VEMap.GetRoute method to get a route. In 
// version 6.1 this method is deprecated and a new VEMap.GetDirections 
// method is used to display multi-point routes.
///////////////////////////////////////////////////////////////////////////////////////////////
function OnGotRoute(route) {

    var routeinfo = "";
    var steps = "";
    var stepsColor = "#000000";
    var len = route.Itinerary.Segments.length;

    var j = 0;
    for (var i = 0; i < len; i++) {
        if (route.Itinerary.Segments[i].Distance != null) {
            if ((j % 2) == 1)
                steps += '<tr class="trnorm">';
            else
                steps += '<tr class="trnorm2">';

            if (route.Itinerary.Segments[i].Distance != null) {
                stepsColor = "#000000";
                if (route.Itinerary.Segments[i].Instruction.indexOf('Start at') == 0)
                    stepsColor = "#068200";
                else if (route.Itinerary.Segments[i].Instruction.indexOf('Arrive at') == 0)
                    stepsColor = "#ff0000";

                steps += '<td class="tdnorm2" style="padding-left:5px;"><font color="' + stepsColor + '">' + route.Itinerary.Segments[i].Instruction + '</font></td>';
                steps += '<td class="tdnorm" style="padding-right:5px;" nowrap><font color="' + stepsColor + '">' + route.Itinerary.Segments[i].Distance + ' ' + route.Itinerary.DistanceUnit + '</font></td>';
            }
            else {
                stepsColor = "#e45c12";
                steps += '<td class="tdnorm2" style="padding-left:5px;padding-right:5px;" colspan="2"><font color="' + stepsColor + '">' + route.Itinerary.Segments[i].Instruction + '</font></td>';
            }
            steps += '</tr>';

            j++;
        }
    }

    routeinfo = '<div style="margin-bottom:10px; padding:5px 13px 10px 13px; width:580px; border:solid 1px #c4c2c2;">'
			+ '		<table border="0" cellpadding="0" cellspacing="4" width="100%">'
			+ '			<tr>'
			+ '				<td style="padding-top:4px;" nowrap="nowrap"><b>Route info:</b></td>'
			+ '			</tr>'
			+ '		</table>'
			+ '		<table width=100% cellspacing=0 cellpadding=0 border=0>'
			+ '			<tr>'
			+ '				<td width=6 height=6><img src="/pages/images/taAssets/corner-ul-sp.gif"></td>'
			+ '				<td class="upcurve"><img src="/pages/images/taAssets/spacer.gif" width=1 height=1></td>'
			+ '				<td width=6 height=6><img src="/pages/images/taAssets/corner-ur-sp.gif"></td>'
			+ '			</tr>'
			+ '		</table>'
			+ '		<TABLE cellSpacing=0 cellpadding=1 class="tbl2" width=100% border=0>'
			+ '			<TR class="trhead">'
			+ '				<TD style="padding-left:5px;">Instructions</TD>'
			+ '				<TD align="right" style="padding-right:5px;">Distance</TD>'
			+ '			</TR>' + steps
			+ '		</table>'
			+ '		<table width=100% cellspacing=0 cellpadding=0 border=0>'
			+ '			<tr>'
			+ '				<td width=6 height=6 class="grey1"><img src="/pages/images/taAssets/corner-ll-outline-white.gif" width=6 height=6></td>'
			+ '				<td class="downcurve"><img src="/pages/images/taAssets/spacer.gif" width=1 height=1></td>'
			+ '				<td width=6 height=6 class="grey1"><img src="/pages/images/taAssets/corner-lr-outline-white.gif" width=6 height=6></td>'
			+ '			</tr>'
			+ '		</table>'
			+ '		<table border="0" cellpadding="0" cellspacing="4" width="100%">'
			+ '			<tr>'
			+ '				<td style="padding-top:4px;" nowrap="nowrap"><b>Total distance:</b> ' + route.Itinerary.Distance + ' ' + route.Itinerary.DistanceUnit + '</td>'
			+ '			</tr>'
			+ '		</table>'
			+ '	</div>';



    //alert(routeinfo);
    $(clicked).innerHTML = routeinfo;
    $(clicked).style.display = 'block';

    previousClicked = "";
}

//////////////////////////////////////////////////////////////////////////////////////
// New Method - Used for Version 6.1
//////////////////////////////////////////////////////////////////////////////////////
function NewOnGotRoute(route) {

    var routeinfo = "";
    var steps = "";
    var stepsColor = "#000000";
    //var len = route.RouteLegs.length;

    // Unroll route and populate DIV
    var legs = route.RouteLegs;
    var leg = null;
    var turnNum = 0;  // The turn #
    var legDistance = "";

    // Get intermediate legs
    for (var i = 0; i < legs.length; i++) {
        // Get this leg so we don't have to derefernce multiple times
        leg = legs[i];  // Leg is a VERouteLeg object

        // Unroll each intermediate leg
        var turn = null;  // The itinerary leg
        var legDistance = null;  // The distance for this leg

        for (var j = 0; j < leg.Itinerary.Items.length; j++) {
            turnNum++;

            turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object

            if ((j % 2) == 1)
                steps += '<tr class="trnorm">';
            else
                steps += '<tr class="trnorm2">';

            stepsColor = "#000000";
            if (leg.Itinerary.Items[j].Text.indexOf('Depart') > -1) {
                stepsColor = "#068200";
            }
            else if (leg.Itinerary.Items[j].Text.indexOf('Arrive') > -1) {
                stepsColor = "#ff0000";
            }

            legDistance = leg.Itinerary.Items[j].Distance.toFixed(2);

            steps += '<td class="tdnorm2" style="padding-left:5px;"><font color="' + stepsColor + '">' + leg.Itinerary.Items[j].Text + '</font></td>';
            steps += '<td class="tdnorm" style="padding-right:5px;" nowrap><font color="' + stepsColor + '">' + legDistance + ' km</font></td>';

            steps += '</tr>';
        }
    }

    routeinfo = '<div style="margin-bottom:10px; padding:5px 13px 10px 13px; width:580px; border:solid 1px #c4c2c2;">'
			+ '		<table border="0" cellpadding="0" cellspacing="4" width="100%">'
			+ '			<tr>'
			+ '				<td style="padding-top:4px;" nowrap="nowrap"><b>Route info:</b></td>'
			+ '			</tr>'
			+ '		</table>'
			+ '		<table width=100% cellspacing=0 cellpadding=0 border=0>'
			+ '			<tr>'
			+ '				<td width=6 height=6><img src="/pages/images/taAssets/corner-ul-sp.gif"></td>'
			+ '				<td class="upcurve"><img src="/pages/images/taAssets/spacer.gif" width=1 height=1></td>'
			+ '				<td width=6 height=6><img src="/pages/images/taAssets/corner-ur-sp.gif"></td>'
			+ '			</tr>'
			+ '		</table>'
			+ '		<TABLE cellSpacing=0 cellpadding=1 class="tbl2" width=100% border=0>'
			+ '			<TR class="trhead">'
			+ '				<TD style="padding-left:5px;">Instructions</TD>'
			+ '				<TD align="right" style="padding-right:5px;">Distance</TD>'
			+ '			</TR>' + steps
			+ '		</table>'
			+ '		<table width=100% cellspacing=0 cellpadding=0 border=0>'
			+ '			<tr>'
			+ '				<td width=6 height=6 class="grey1"><img src="/pages/images/taAssets/corner-ll-outline-white.gif" width=6 height=6></td>'
			+ '				<td class="downcurve"><img src="/pages/images/taAssets/spacer.gif" width=1 height=1></td>'
			+ '				<td width=6 height=6 class="grey1"><img src="/pages/images/taAssets/corner-lr-outline-white.gif" width=6 height=6></td>'
			+ '			</tr>'
			+ '		</table>'
			+ '		<table border="0" cellpadding="0" cellspacing="4" width="100%">'
			+ '			<tr>'
			+ '				<td style="padding-top:4px;" nowrap="nowrap"><b>Total distance:</b> ' + route.Distance.toFixed(1) + ' km </td>'
			+ '			</tr>'
			+ '		</table>'
			+ '	</div>';

    //alert(routeinfo);
    $(clicked).innerHTML = routeinfo;
    $(clicked).style.display = 'block';

    previousClicked = "";

}

function getPoints(streetAddress, suburb, state, postcode, country, name) {
    clicked = name;
    if (previousClicked == "") {
        getPosition1(streetAddress, suburb, state, postcode, country, name);
    }
    else {
        $('start' + previousClicked).innerHTML = "";
        $('start' + previousClicked).style.display = 'none';

        getPosition1(streetAddress, suburb, state, postcode, country, name);
    }
}

function getPosition1(streetAddress, suburb, state, postcode, country, name) {
    scroll(0, 0);
    var address = "";

    previousClicked = name;

    //address = streetAddress + ", " + suburb + ", " + state + ", " + postcode + ", " + country;
    address = ((streetAddress.length == 0) ? "" : (streetAddress + ", ")) + ((suburb.length == 0) ? "" : (suburb + ", ")) + ((state.length == 0) ? "" : (state + ", ")) + ((postcode.length == 0) ? "" : (postcode + ", ")) + ((country.length == 0) ? "" : (country));
    if ((address.substr(address.length - 1, 1)) == ",")
        address = address.substr(0, address.length - 1);

    strPos1 = '<div style="margin-bottom:10px; padding:5px 13px 10px 13px; width:580px; border:solid 1px #c4c2c2;">'
			+ '		<table border="0" cellpadding="0" cellspacing="4" width="100%">'
			+ '			<tr>'
			+ '				<td style="padding-top:4px;" nowrap="nowrap"><b>Please enter your location:</b></td>'
			+ '			</tr>'
			+ '			<tr>'
			+ '				<td><table border="0" cellpadding="0" cellspacing="0" width="100%">'
			+ '					<tr>'
			+ '						<td style="padding-top:4px;padding-right:4px;" nowrap="nowrap">Street no.</td><td style="padding-top:4px;padding-right:4px;"><input type="text" class="field19" name="pos1_streetNumber" id="pos1_streetNumber" size="15" value="' + startpt_streetNumber + '" /></td>'
			+ '						<td style="padding-top:4px;padding-right:4px;" nowrap="nowrap" align="right">Street name</td><td style="padding-top:4px;" align="right"><input type="text" class="field19" name="pos1_streetName" id="pos1_streetName" size="60" value="' + startpt_streetName + '" /></td>'
			+ '					</tr>'
			+ '				</table></td>'
			+ '			</tr>'
			+ '			<tr>'
			+ '				<td><table border="0" cellpadding="0" cellspacing="0" width="100%">'
			+ '					<tr>'
			+ '						<td style="padding-top:4px;padding-right:4px;" nowrap="nowrap">Suburb</td><td style="padding-top:4px;padding-right:4px;"><input type="text" class="field19" name="pos1_suburb" id="pos1_suburb" size="50" value="' + startpt_suburb + '" /></td>'
			+ '						<td style="padding-top:4px;padding-right:4px;" nowrap="nowrap">State</td><td style="padding-top:4px;padding-right:4px;"><select class="field19" name="pos1_state" id="pos1_state"><option value="ACT">ACT</option><option value="NSW">NSW</option><option value="NT">NT</option><option value="QLD">QLD</option><option value="SA">SA</option><option value="TAS">TAS</option><option value="VIC">VIC</option><option value="WA">WA</option></select></td>'
			+ '						<td style="padding-top:4px;padding-right:4px;" nowrap="nowrap">Postcode</td><td style="padding-top:4px;padding-right:4px;"><input type="text" class="field19" name="pos1_postcode" id="pos1_postcode" size="5" value="' + startpt_postcode + '" /></td>'
			+ '						<td style="padding-top:4px;padding-left:4px;" align="right"><input type="image" onmouseover="src=\'images/taAssets/but_go_ro.gif\'" onmouseout="src=\'images/taAssets/but_go.gif\'" onclick="javascript:getDirections(\'' + address + '\');" src="images/taAssets/but_go.gif"/></td></td>'
			+ '					</tr>'
			+ '				</table></td>'
			+ '			</tr>'
			+ '		</table>'
			+ '	</div>';

    //alert('<input type="text" name="pos1" id="pos1" size="25" value="Type your location." /><input type="button" value="submit" onclick="javascript:getDirections(\'' + address + '\');"/>';
    $('start' + clicked).innerHTML = strPos1;
    $('start' + clicked).style.display = 'block';

    if (startpt_state == "")
        $('pos1_state').value = state;
}

function getDirections(address) {

    var pos1;
    if ($F('pos1_streetNumber') == "") {
        alert("Please enter the full address of your location.");
        $('pos1_streetNumber').focus();
        return;
    }
    else if ($F('pos1_streetName') == "") {
        alert("Please enter the full address of your location.");
        $('pos1_streetName').focus();
        return;
    }
    else if ($F('pos1_suburb') == "") {
        alert("Please enter the full address of your location.");
        $('pos1_suburb').focus();
        return;
    }
    else if ($F('pos1_postcode') == "") {
        alert("Please enter the full address of your location.");
        $('pos1_postcode').focus();
        return;
    }
    else if (isNaN($F('pos1_postcode')) || $F('pos1_postcode').length != 4) {
        alert("Please enter a valid Australian postode.");
        $('pos1_postcode').focus();
        return;
    }
    else {
        startpt_streetNumber = $F('pos1_streetNumber');
        startpt_streetName = $F('pos1_streetName');
        startpt_suburb = $F('pos1_suburb');
        startpt_state = $F('pos1_state');
        startpt_postcode = $F('pos1_postcode');
        pos1 = startpt_streetNumber + ", " + startpt_streetName + ", " + startpt_suburb + ", " + startpt_state + ", " + startpt_postcode + ", Australia";
        /*startpt = $F('pos1');
        if (pos1.indexOf("Australia") == -1)
        {
        pos1 = pos1 + ", Australia";
        }*/
        if (address.indexOf(', Australia') == -1)
            address += ', Australia';
        if (pos1.indexOf(', Australia') == -1)
            pos1 += ', Australia';

        $('start' + clicked).innerHTML = '';
        $('start' + clicked).style.display = 'none';

        var dirPos1 = escape(pos1.replace(", ,", ",").replace(",,", ",").replace(", ,", ","));
        var dirPos2 = escape(address.replace(", ,", ",").replace(",,", ",").replace(", ,", ","));

        // Deprecated Method - Use map.GetDirections() instead!
        //map.GetRoute(escape(pos1.replace(", ,", ",").replace(",,", ",").replace(", ,", ",")), escape(address.replace(", ,", ",").replace(",,", ",").replace(", ,", ",")), [VEDistanceUnit.Kilometers], [VERouteType.Quickest], OnGotRoute);

        // New code for version 6.1
        ///////////////////////////////////////////////////////////////////////////////
        var locations;
        locations = new Array(dirPos1, dirPos2);

        var options = new VERouteOptions;
        // Call this function when map route is determined:
        options.RouteCallback = NewOnGotRoute;
        // Show as Kilometers
        options.DistanceUnit = VERouteDistanceUnit.Kilometer;
        // Show the disambiguation dialog
        options.ShowDisambiguation = true;

        map.GetDirections(locations, options);
        ///////////////////////////////////////////////////////////////////////////////
    }
}

function submitSignup() {
    var signupForm = document.getElementById('frmSignup');
    var name = 0;
    var surname = 0;
    var email = 0;
    var policy = 0;

    //alert(signupForm.cbxAccept.checked);

    if (signupForm.txtname_nav.value == '' || signupForm.txtname_nav.value == 'First') {
        name = 1;
    }

    if (signupForm.txtsurname_nav.value == '' || signupForm.txtsurname_nav.value == 'Last') {
        surname = 1;
    }

    if (signupForm.txtemail_nav.value == '') {
        email = 1;
    }
    else {
        if (isValidEmail(signupForm.txtemail_nav.value) == false) {
            email = 1;
        }
    }

    if (signupForm.cbxAccept.checked == false) {
        policy = 1;
    }

    changeSignupField(name, surname, email, policy);

    //alert(policy);

    if ((name == 1) || (surname == 1) || (email == 1) || (policy == 1)) {
        return false;
    }
}

function changeSignupField(arg1, arg2, arg3, arg4) {
    var signupForm = document.getElementById('frmSignup');
    var emailValue = signupForm.txtemail_nav.value;
    fixFields();
    if (arg1 == 1) {
        document.getElementById('dv_name').innerHTML = "<input type=\"text\" value=\"First\" name=\"txtname_nav\" id=\"txtname_nav\" class=\"fieldsmall\" style=\"margin-top:4px;border:solid 1px red;\" onFocus=\"this.value = '';\" onBlur=\"FirstnameField();\" />";
    }
    if (arg2 == 1) {
        document.getElementById('dv_surname').innerHTML = "<input type=\"text\" value=\"Last\" name=\"txtsurname_nav\" id=\"txtsurname_nav\" class=\"fieldsmall\" style=\"margin-top:4px;border:solid 1px red;\" onFocus=\"this.value = '';\" onBlur=\"SurnameField();\" />";
    }
    if (arg3 == 1) {
        document.getElementById('dv_email').innerHTML = "<input type=\"text\" value=\"" + emailValue + "\" name=\"txtemail_nav\" id=\"txtemail_nav\" class=\"fieldemail\" style=\"border:solid 1px red;\" />";
    }
    if (arg4 == 1) {
        document.getElementById('accept').innerHTML = "<span style=\"color:red;\">I accept Tennis Australia's</span>";
    }
}

function fixFields() {
    var signupForm = document.getElementById('frmSignup');
    var nameValue = signupForm.txtname_nav.value;
    var surnameValue = signupForm.txtsurname_nav.value;
    var emailValue = signupForm.txtemail_nav.value;

    document.getElementById('dv_name').innerHTML = "<input type=\"text\" value=\"" + nameValue + "\" name=\"txtname_nav\" id=\"txtname_nav\" class=\"fieldsmall\" style=\"margin-top:4px;\"  onFocus=\"this.value = '';\" onBlur=\"FirstnameField();\" />";
    document.getElementById('dv_surname').innerHTML = "<input type=\"text\" value=\"" + surnameValue + "\" name=\"txtsurname_nav\" id=\"txtsurname_nav\" class=\"fieldsmall\" style=\"margin-top:4px;\" onFocus=\"this.value = '';\" onBlur=\"SurnameField();\" />";
    document.getElementById('dv_email').innerHTML = "<input type=\"text\" value=\"" + emailValue + "\" name=\"txtemail_nav\" id=\"txtemail_nav\" class=\"fieldemail\" />"
    document.getElementById('accept').innerHTML = "I accept Tennis Australia's";
}

function isValidEmail(strEmail) {
    validRegExp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    //strEmail = document.forms[0].email.value;

    // search email text for regular exp matches
    if (strEmail.search(validRegExp) == -1) {
        //alert('A valid e-mail address is required.\nPlease amend and retry');
        return false;
    }
    return true;
}

/***************************************************************
***************************************************************
include/JS/MM_functions.js
***************************************************************
**************************************************************/

function MM_swapImage() { //v3.0

    var i;
    var j = 0;
    var x;
    var 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.0
    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 && document.getElementById) x = document.getElementById(n); return x;
}

function MM_swapImgRestore() { //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]; } 
    }
}

//KL
function showPrintPage(artId, pageId, siteId) {
    var winURL = '/pages/print.aspx?articleid=' + artId + '&id=' + siteId + '&pageId=' + pageId;
    //alert (winURL);
    w = window.open(winURL, "print", "scrollbars,resizable,width=690,height=680");
    w.focus();
}

//EA
function showEmailPage(artId, pageId, siteId) {
    //var winURL = '/pages/print.aspx?articleid=' + artId +  '&id=' + siteId + '&pageId='+pageId;
    //alert (winURL);
    //w = window.open(winURL, "print", "scrollbars,resizable,width=500,height=500");
    //w.focus();
}


function emailToAFriend(sid, nid, pid, type) {
    if (type == 'news')
        window.open("NewsEmailToAFriend.aspx?id=" + sid + "&newsid=" + nid + "&pageId=" + pid, "newsemail", "height=210px,width=684px,scrollbars=yes,location=no,toobar=no");
    else if (type == 'photos')
        window.open("PhotosEmailToAFriend.aspx?id=" + sid + "&galleryid=" + nid + "&pageId=" + pid, "photosemail", "height=210px,width=684px,scrollbars=yes,location=no,toobar=no");
    else
        window.open("ArticleEmailToAFriend.aspx?id=" + sid + "&articleid=" + nid + "&pageId=" + pid, "pagearticleemail", "height=210px,width=684px,scrollbars=yes,location=no,toobar=no");
}

function isNumeric(strString) {
    //  check for valid numeric strings

    var strValidChars = "0123456789.-"
    var strChar
    var blnResult = true

    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i)
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false
        }
    }
    if (!blnResult) {
        alert('Please enter a numeric value')
    }
    return blnResult
}


/***************************************************************
***************************************************************
include/JS/TANielson.js
***************************************************************
**************************************************************/

var _rsCI = "sportal-au";
var _rsCG = "tennisaus";
var _rsDT = 0; // to turn on whether to get the document title, 1=on
var _rsDU = 0; // to turn on or off the applet, 1=on
var _rsDO = 1; // to turn on debug output to the console, 1=on, only works if _rsDU=1 
var _rsX6 = 0; // to force use of applet with XP and IE6, 1=on, only works if _rsDU=1 
var _rsSI = escape(window.location);
var _rsLP = location.protocol.indexOf('https') > -1 ? 'https:' : 'http:';
var _rsRP = escape(document.referrer);
var _rsND = _rsLP + '//secure-au.imrworldwide.com/';

if (parseInt(navigator.appVersion) >= 4) {
    var _rsRD = (new Date()).getTime();
    var _rsSE = 0;
    var _rsSV = "";
    var _rsSM = 0;
    _rsCL = '<scr' + 'ipt language="JavaScript" type="text/javascript" src="' + _rsND + 'v51.js"><\/scr' + 'ipt>';
}
else {
    _rsCL = '<img src="' + _rsND + 'cgi-bin/m?ci=' + _rsCI + '&cg=' + _rsCG + '&si=' + _rsSI + '&rp=' + _rsRP + '" />';
}
document.write(_rsCL);


/***************************************************************
***************************************************************
include/js/flash/flash_sitelogo.js
***************************************************************
**************************************************************/

if ($('divSiteFlashLogo')) {
    var hasRightVersionSiteLogo = DetectFlashVer(8, 0, 22);
    if (hasRightVersionSiteLogo) {  // if we've detected an acceptable version

        var oeTagsSiteLogo = '<object width="134" height="96" style="position:relative; top:0px;padding:0px 0px 0px 0px; margin:0px 0px 0px 15px;" align="middle" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0">';
        oeTagsSiteLogo += '<param name="wmode" value="transparent"/>'
        oeTagsSiteLogo += '<param name="allowScriptAccess" value="sameDomain"><param name="movie" value="/pages/images/flashplayer/' + flashLogoAssetID.replace(".", "") + '.swf"/>'
        oeTagsSiteLogo += '<param name="quality" value="high">'
        oeTagsSiteLogo += '<param name="loop" value="false">'
        oeTagsSiteLogo += '<param name="menu" value="false">'
        oeTagsSiteLogo += '<embed style="position: relative; top:0px;padding:0px 0px 0px 15px; margin:0px 0px 0px 0px;" src="/pages/images/flashplayer/' + flashLogoAssetID.replace(".", "") + '.swf" quality="high" loop="false" menu="false" width="134" height="96" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">'
        oeTagsSiteLogo += '<\/embed>'
        oeTagsSiteLogo += '<\/object>';
        document.getElementById('divSiteFlashLogo').innerHTML = '<a href="HomePage.aspx?id=4&amp;PageId=122&amp;HandlerId=300">' + oeTagsSiteLogo + '</a>';   // embed the flash logo

    } else {  // flash is too old or we can't detect the plugin

        var oeTagsSiteLogo = ''

        // 30/10/07- oeTagsSiteLogo += '<img src="/pages/image.aspx?assetID=' + nonFlashLogoAssetID + '" border="0" style="position:relative;top:-4px;left:0px;" />';
        oeTagsSiteLogo += '<img src="/pages/image.aspx?assetID=' + nonFlashLogoAssetID + '" border="0" style="position:relative; top:0px;padding:0px 0px 0px 0px; margin:0px 0px 0px 15px;" />';

        document.getElementById('divSiteFlashLogo').innerHTML = '<a href="HomePage.aspx?id=4&amp;PageId=122&amp;HandlerId=300">' + oeTagsSiteLogo + '</a>';  // insert non-flash content

    }
}

