    /*
     * Author: Karl O'Leary
     * Company: Emagine Media, http://www.emagine.ie
     * Description: Library of functionality for EM
     *
     * Updated:
     * - 20090507.1252, Karl, added the getVersion and error safe logger function
     * - 20081222, Karl, created
     */


    var version = "1.1";



    // Utility FUNCTIONS =============================================================================================================================================================

    /*
     * try to write messages to the Firebug console and catch any possible error
     */
    function logger(msg) {
        try {
            console.log(new Date+": "+msg);
        }
        catch(err) {}
    }

    function getVersion() {
        return version;
    }

    function pauseMillis(millis) {
        var date = new Date();
        var curDate = null;

        do { curDate = new Date(); }
        while(curDate-date < millis);
    }


    // Google Maps FUNCTIONS =============================================================================================================================================================

    function googleMapsLoad(iid, center_x, center_y, zoom) {
        var map = null;
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById(iid));
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            map.setCenter(new GLatLng(center_x, center_y), zoom);
        }
        return map;
    }

    function googleMapsAddMarker(map, marker_x, marker_y, body) {
        var marker = new GMarker(new GLatLng(marker_x, marker_y));
        GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(body); });
        map.addOverlay(marker);
    }

    function googleMapsUnload() {
        GUnload();
    }



    // Form Validation FUNCTIONS =============================================================================================================================================================

    function validateEmail(eee) {
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return filter.test(eee);
    }


    // PLUGINS =============================================================================================================================================================


    /*
     * This function displays an image as a tooltip.
     * The code has been modified so that the image displays to the left of the cursor.
     * The a tag needs to hold 2 urls, the of the image to display, href
     * Because Peter wants the Flickr page to display, the rel attribute hold the url of the landing page in Flickr
     */
    this.imagePreview = function(){
        var xOffset = -20;
        var yOffset = 20;
        var i_width = 0;

        $("a.preview").hover(function(e){
            var iii = $(this).attr("rel");
            this.t = this.title;
            this.title = "";
            var c = (this.t != "") ? "<br/>" + this.t : "";
            //$("body").append("<div id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</div>");
            $("body").append("<div id='preview'><img src='"+ iii +"' alt='Image preview' />"+ c +"</div>");
            $("#preview").css("top",(e.pageY + yOffset) + "px").css("left",(e.pageX + xOffset - i_width) + "px").fadeIn("fast");
        },function(){
            this.title = this.t;
            $("#preview").remove();
        });
        $("a.preview").mousemove(function(e){
            i_width = $("#preview img").width();
            $("#preview").css("top",(e.pageY + yOffset) + "px").css("left",(e.pageX + xOffset - i_width) + "px");
        });
        /*
        $("a.preview").bind("click", function(e){
            window.location.href = $(this).attr("rel");
            return false;
        });
        */
    };

    jQuery.url = function() {
        var segments = {};
        var parsed = {};
        /**
        * Options object. Only the URI and strictMode values can be changed via the setters below.
        */
        var options = {
            url : window.location, // default URI is the page in which the script is running
            strictMode: false, // 'loose' parsing by default
            key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query
            q: {
                name: "queryKey",
                parser: /(?:^|&)([^&=]*)=?([^&]*)/g
            },
            parser: {
                strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, // more intuitive, fails on relative paths and deviates from specs
                loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ //less intuitive, more accurate to the specs
            }
        };

        /**
         * Deals with the parsing of the URI according to the regex above.
         * Written by Steven Levithan - see credits at top.
         */
        var parseUri = function()	{
            str = decodeURI( options.url );
            var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
            var uri = {};
            var i = 14;
            while ( i-- ) {
                uri[ options.key[i] ] = m[i] || "";
            }
            uri[ options.q.name ] = {};
            uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
                if ($1) {
                    uri[options.q.name][$1] = $2;
                }
            });
            return uri;
        };

        /**
         * Returns the value of the passed in key from the parsed URI.
         *
         * @param string key The key whose value is required
         */
        var key = function( key )	{
            if ( ! parsed.length )		{
                setUp(); // if the URI has not been parsed yet then do this first...
            }
            if ( key == "base" ){
                if ( parsed.port !== null && parsed.port !== "" )			{
                    return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";
                }
                else{
                    return parsed.protocol+"://"+parsed.host+"/";
                }
            }

            return ( parsed[key] === "" ) ? null : parsed[key];
        };

        /**
         * Returns the value of the required query string parameter.
         *
         * @param string item The parameter whose value is required
         */
        var param = function( item )	{
            if ( ! parsed.length )		{
                setUp(); // if the URI has not been parsed yet then do this first...
            }
            return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
        };

        /**
         * 'Constructor' (not really!) function.
         *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments.
         */
        var setUp = function()	{
            parsed = parseUri();
            getSegments();
        };

        /**
         * Splits up the body of the URI into segments (i.e. sections delimited by '/')
         */
        var getSegments = function()	{
            var p = parsed.path;
            segments = []; // clear out segments array
            segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
        };
        return {
            /**
             * Sets the parsing mode - either strict or loose. Set to loose by default.
             *
             * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
             */
            setMode : function( mode )		{
                strictMode = mode == "strict" ? true : false;
                return this;
            },

            /**
             * Sets URI to parse if you don't want to to parse the current page's URI.
             * Calling the function with no value for newUri resets it to the current page's URI.
             *
             * @param string newUri The URI to parse.
             */
            setUrl : function( newUri )		{
                options.url = newUri === undefined ? window.location : newUri;
                setUp();
                return this;
            },

            /**
             * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
             * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
             *
             * If no integer is passed into the function it returns the number of segments in the URI.
             *
             * @param int pos The position of the segment to return. Can be empty.
             */
            segment : function( pos )		{
                if ( ! parsed.length )			{
                    setUp(); // if the URI has not been parsed yet then do this first...
                }
                if ( pos === undefined )			{
                    return segments.length;
                }
                return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
            },
            attr : key, // provides public access to private 'key' function - see above
            param : param // provides public access to private 'param' function - see above
        };
    }();