/* Init JQuery plugins & widgets */
$(document).ready(function(){
    // assign the ColorBox event to elements
    $("a[rel='colorbox']").colorbox({slideshow:false, fixed:true, width:'80%', height:'90%'  });
    // assign the standard tooltip function to elements
    $(".jqToolTip").jqToolTipHover(  );


});

function scrollToID(id){
      $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}
function scrollToTop( ){
       $('html,body').animate({scrollTop: 0},'slow');
}


jQuery.fn.jqAlert = function (msg) {
    jqMask(false);
}
jQuery.fn.jqMask = function(modal) {
    // Create mask
    $('<div/>', {
        name: 'jqIFrameMask',
        id:   'jqIFrameMask',
        style: 'position: absolute; top:0; left:0; display:none; width:100%; height:100%; background: #333;z-index: 99999; '
    }).appendTo('body');

    //Get the document height and width
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    //Set height and width to mask to fill up the whole screen
    $('#jqIFrameMask').css({'width':maskWidth,'height':maskHeight});

    $('#jqIFrameMask').fadeTo("500",0.8);

};
(function( $ ){
    $.fn.jqToolTipHover = function( options ) {

    //set default options
    var defaults = {
        popupID    : 'jqToolTip',
        position: 'mouse',
        offsetX: 0,
        offsetY: 0
    };

    //call in the default otions
    var options = $.extend(defaults, options);

    // Create the popup tooltip container
    $("body").append("<div id='" + options.popupID + "' style='display: none;'></div>");

    var jqPopupID = "#" + options.popupID;

    /* redisplay or hide when the user moves over/off the popup tooltip */
    $("#" + options.popupID).hover(
        function(e) {
            if ( ! $(jqPopupID).is(":visible"))$(jqPopupID).show();
        },
        function() {
            if ( $(jqPopupID).is(":visible"))$(jqPopupID).hide()
    	}
    );


     //assign hover handlers to each element that is selected
     return this.each(function() {
        var titleText;
        var el = $(this);
        el.bind('mouseenter', {myOptions: options}, function(event) {

            elOptions = event.data.myOptions;
            var jqPopupID = "#" + elOptions.popupID;
            if ( $(jqPopupID).is(":visible"))$(jqPopupID).hide()
            /* Get and remove title */
            titleText = el.attr('title');
            el.removeAttr("title");
            $(jqPopupID).html(titleText);

            if (elOptions.position=='mouse'){
                var left = event.pageX;// - this.offsetLeft;
                var top = event.pageY - $(jqPopupID).height();// - this.offsetTop;
            }
            else{
                var position = el.offset();
                var top = position.top - $(jqPopupID).height() + elOptions.offsetY;
                var left = position.left - $(jqPopupID).width() + elOptions.offsetX ;
            }
            $(jqPopupID).css("top", top  + "px");
            $(jqPopupID).css("left", left  + "px")
            $(jqPopupID).show();
         });

        el.bind('mouseleave', {myOptions: options}, function(event) {
            elOptions = event.data.myOptions;
            var jqPopupID = "#" + elOptions.popupID;
            el.attr('title', titleText);
            $(jqPopupID).hide();
         });
     });

  };
})( jQuery );

(function( $ ){
    $.fn.XjqToolTipHover = function( options ) {

    //set default options
    var defaults = {
        popupID    : 'jqToolTip',
        offsetX: 50,
        offsetY: 0
    };

    //call in the default otions
    var options = $.extend(defaults, options);
    // Create the popup tooltip container
    $("body").append("<div id='jqToolTip' style='display: none;'><div id='jqToolTipText'></div></div>");
    /* Hide if close clicked */
    $("#jqToolTipClose").click( function(e){ $('#jqToolTip').hide() });
    /* redisplay or hide when the user moves over/off the popup tooltip */
    $("#jqToolTip").hover(
        function(e) {
            if ( ! $('#jqToolTip').is(":visible"))$('#jqToolTip').show();
        },
        function() {
            if ( $('#jqToolTip').is(":visible"))$('#jqToolTip').hide()
    	}
    );


     //assign hover handlers to each element that is selected
     return this.each(function(options){
        var el = $(this);
        var titleText;

            el.hover(
                function(e) {
                    if ( $('#jqToolTip').is(":visible"))$('#jqToolTip').hide()

                    //if ( ! $('#jqToolTip').is(":visible")  ){
    		        /* Mouse Enter Function */
                    /* Get and remove title */
                     titleText = el.attr('title');
                     $(this).removeAttr("title");
                     $('#jqToolTipText').html(titleText);


                    var position = el.offset();

                    $('#jqToolTip').css("top", position.top - $('#jqToolTip').height() + options.offsetX + "px");
                    $('#jqToolTip').css("right", position.left + -30  + "px")
                     $('#jqToolTip').show();
                    //}
    			},
                function() {
    		         /* Mouse Leave Function */
                     /* Restore title */
                     el.attr('title', titleText);
                      $('#jqToolTip').hide();
    	        });



    });

  };
})( jQuery );

 /* ===============================================================================
clearOnFocus: onfocus='clearOnFocus(this);'
 ===============================================================================*/
function jqClearOnFocus(el){
    if ( $(el).hasClass('clearOnFocus') ){
        $(el).val('');
        $(el).removeClass('clearOnFocus');
    }
}
 /* ===============================================================================
createMap:
 $(selector).createMap();
 ===============================================================================*/
(function( $ ){

    $.fn.createMap = function( arMarkers, options ) {
        var defaults  = {
            'infoWinHeight': 150,
            'infoWinWidth': 150,
            'infoWinClass' : 'gmInfoWindow',
            'singleMarkerZoom':10
        };

        // If options exist,  merge them with default settings
        var options = $.extend(defaults, options);

        containerID = this.attr('id' ) ; //   current selector id (eg 'myMap' )


        /* Create the map options */
        var mapOptions = {
            zoom: 5,
            mapTypeControl: true,
            mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
            navigationControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        /* create the map */
        var map = new google.maps.Map(document.getElementById(containerID), mapOptions);


        /* Do we have any markers ? */
        if (  arMarkers.length > 0 ){
            map.markers = [];/* to hold markers in this map for later reference */
            map.markerStore = [];
            /* Add listener to close the info windo when the map is clicked */
            google.maps.event.addListener(map, 'click', function() { infowindow.close(); });


            /* Create bounds object */
            if(arMarkers.length > 0) var bounds = new google.maps.LatLngBounds();

            /* Add markers to the map */
            var nextID=1; // in case we're not passed an id in teh marker array
            for (var i = 0;i < arMarkers.length; i += 1) {
                var id = (arMarkers[i].id) ? arMarkers[i].id : nextID++;
                var lat = arMarkers[i].lat;
                var long = arMarkers[i].long;
                var title = arMarkers[i].title;
                var html = arMarkers[i].html;
                var iconURL = arMarkers[i].iconURL;
                var point = new google.maps.LatLng(lat,long);
                if (iconURL){
                    var icon = new google.maps.MarkerImage(iconURL );
                }
                else var icon=null;
                createMarker(id, point,title, html, icon);
                if(arMarkers.length > 0) bounds.extend(point);
            };
         }

         if( arMarkers.length == 1){
            map.setCenter( point) ;
            map.setZoom( options.singleMarkerZoom);
         }
         else if( arMarkers.length > 1){
            map.fitBounds(bounds);
         }
         else{
            // No markers so centre map on Dunsop Bridge Clitheroe, Lancashire
            var point = new google.maps.LatLng(53.945187,-2.520681);
            map.setCenter( point) ;
            map.setZoom( 6);
         }


        var infowindow = new google.maps.InfoWindow( );

        // A function to create the marker and set up the event window function
        function createMarker(id, latlng, name, html, gmIcon) {
            var contentString = html;
            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: gmIcon,
                zIndex: Math.round(latlng.lat()*-100000)<<5
            });
            map.markers.push(marker);
            map.markerStore[id]=marker;
            /* Function to populate and open the info window */
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent(contentString);
                infowindow.open(map,marker);
                /* Fix what appears to be a GM bug with scroll bars? */
                $('.' + options.infoWinClass).parent().parent().addClass('gmInfoWindowRoot')
                $('.' + options.infoWinClass).parent().parent().css('overflow-y','visible')
                $('.' + options.infoWinClass).parent().css('overflow-y','visible')
            });

        }

        /* ========       PUBLIC FUNCTIONS  ===============*/
        /* reset: Reset the map size, center and bounds - called after 'revealing' an initally hidden map */
        this.reset = function() {
            point = map.getCenter();
            google.maps.event.trigger(map, 'resize');
            var bounds = new google.maps.LatLngBounds();
            for(var i=0; i<map.markers.length; i++){
                bounds.extend( map.markers[i].position );
            }
            map.setCenter( point) ;
            map.fitBounds(bounds);
        }

        /* openInfoWindow:  manually opens an infowindow */
        this.openInfoWindow = function(id){
            var marker = map.markerStore[id];
            google.maps.event.trigger(marker, 'click');
        }

        return (this);

    }

})(jQuery);


/* ===============================================================================
 sectionToggle:
 Alias for revealer plugin -  open/close an associated element when a link (normally <a>)
 is clicked. The association is based on a rel attribute.

 Usage eXAMPLES:
 <a class='blockTitleClass' rel='block_1'>My Block Title</a>
 <div id='block_1' class='blockContent'>My Block Content</div>

 $('.blockTitleClass').revealer();
 ===============================================================================*/
(function( $ ){

    $.fn.sectionToggle = function( selector, options ) {
        var defaults  = {
        'appendTag'     : '',
        'openFirst'     : true,
        'addTriggers'   : false,
        'exclusiveOpen' : true,
        'openID'        : false,
        'effect'        : 'fade',
        'speed'         : '800',
        'openText'      : '',
        'closeText'     : '',
        'revealedClass' : 'active',
        'concealedClass' : 'inactive',
        'scrollTop'     : true
        };

        // If options exist,  merge them with default settings
        var options = $.extend(defaults, options);

         $(selector).revealer(options);
    }
})(jQuery);
/* ===============================================================================
 revealer plugin - attaches a 'reveal' link to a selection. The link will open/close
 an associated element when clicked. The association is based on a rel attribute.

 Usage eXAMPLES:
 <a class='blockTitleClass' rel='block_1'>My Block Title</a>
 <div id='block_1' class='blockContent'>My Block Content</div>

 $('.blockTitleClass').revealer();
 ===============================================================================*/
(function( $ ){

    $.fn.revealer = function( options ) {

        var defaults  = {
        'appendTag'     : 'a',
        'openFirst'     : false,
        'addTriggers'   : true,
        'exclusiveOpen' : false,
        'openID'        : false,
        'effect'        : 'slide',
        'speed'         : '800',
        'openText'      : 'Open',
        'closeText'     : 'Close',
        'revealedClass' : 'revealed',
        'concealedClass' : 'concealed',
        'scrollTop'     : false

        };

        // If options exist,  merge them with default settings
        var options = $.extend(defaults, options);

        // DOnt open first element if an openID has been passed
        if (options.openID) options.openFirst = false;

        // Process each element in the selection
        this.each(function(index) {

            obj = $(this);

            var relBlockID = obj.attr('rel'); // id of the block rel-ated to this selection
            var block = $('#' + relBlockID); // the block rel-ated to this selection
            if (index == 0  &&  options.openFirst) {
                // add reveal triggers unless they are already setup
                if (options.addTriggers) obj.append('<a class="revealer ' + options.revealedClass + ' ">' + options.closeText + '</a>');// Attach the revealer element
                else obj.addClass('revealer ' + options.revealedClass );
            }
            else{
                block.addClass( options.concealedClass  ).hide();  // add the concealed class and hide the block
                if (options.addTriggers) obj.append('<a class="revealer ' + options.concealedClass  + '">' + options.openText + '</a>');// Attach the revealer element
                else obj.addClass('revealer ' + options.concealedClass );
            }
        });

        // Start of  click handler attacjed to all the revealers
        $('.revealer').click(function() {
            var clicker = $(this);

            // if exclusiveOpen = true close all open blocks
            if (options.exclusiveOpen){
               $('.revealer.' + options.revealedClass).each(function(index) {
                  $.fn.revealer.close($(this));

               });

            }

            if (clicker.hasClass(options.concealedClass )){ // SHOW IT
               $.fn.revealer.open(clicker);

            }
            else {                              // HIDE It
               $.fn.revealer.close(clicker);
            }

            return(false);
        });
        // End of  click handler attacjed to all the revealers

        //  Open block  function
        $.fn.revealer.open = function(clicker) {
            if (options.addTriggers) {
                var parent =clicker.parent();
                var blockID = parent.attr('rel');
            }
            else blockID = clicker.attr('rel');

            var block = $('#' + blockID);
            if (options.effect=='slide') block.slideDown(options.speed) ;
            else if (options.effect=='fade') block.fadeIn(options.speed) ;
            block.removeClass('concealed').addClass( options.revealedClass);
            clicker.removeClass('concealed').addClass( options.revealedClass);
            if (options.addTriggers) clicker.html(options.closeText);      // show close text
            if (options.scrollTop) scrollToTop() ;
        };


         //  Close  block function
        $.fn.revealer.close = function(clicker) {
            if (options.addTriggers) {
                var parent =clicker.parent();
                var blockID = parent.attr('rel');
            }
            else blockID = clicker.attr('rel');

            var block = $('#' + blockID);
            block.removeClass(options.revealedClass).addClass(options.concealedClass );
            clicker.removeClass(options.revealedClass).addClass(options.concealedClass );
            if (options.addTriggers) clicker.html(options.openText);    // show open text
            if (options.effect=='slide') block.slideUp(options.speed) ;
            else if (options.effect=='fade') block.fadeOut(options.speed);
        }

        // OPen an element if a openID has been passed
        if (options.openID){
               $('#' + options.openID).find(".revealer").click() ;
        }
    };
    return(this);
})(jQuery);

/* ===============================================================================
 iFrame plugin -
 Usage:
    $.fn.jqIframe(href, {options });
===============================================================================  */
/* Shorthand calls */
function jqIFrame(url, ifWidth, ifHeight){ return ( $.fn.jqIframe(url, {width:ifWidth, height: ifHeight }) ); }
function jqIFrameClose(reloadParent){
    $.fn.jqIframe.closePopup();
    if (reloadParent) window.location.reload();;
}
(function( $ ){

    $.fn.jqIframe = function( url, options ) {

        var defaults  = {
        'width'     : '640',
        'height'    : '480',
        'lockOuterID': '',
        'autoHeight'  :true
        };

        // If options exist,  merge them with default settings
        var options = $.extend(defaults, options);

        /* =========== INTERNAL FUNCTIONS START ============== */
        //  Show Mask  function
        $.fn.jqIframe.showMask = function() {
            // Create mask
            $('<div/>', {
                name: 'jqIFrameMask',
                id:   'jqIFrameMask',
                style: 'position: absolute; top:0; left:0; display:none; width:100%; height:100%; background: #333;z-index: 99999; '
            }).appendTo('body');

            //Get the document height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            //Set height and width to mask to fill up the whole screen
            $('#jqIFrameMask').css({'width':maskWidth,'height':maskHeight});

            $('#jqIFrameMask').fadeTo("500",0.8);
            if (options.lockOuterID) $('#' + options.lockOuterID).css("position","fixed");
        };

        //  Remove popup & mask  function
        $.fn.jqIframe.closePopup = function() {
            $('#jqIFramePopup').fadeOut().remove();
            $('#jqIFrameMask').fadeOut().remove();
            if (options.lockOuterID) $('#' + options.lockOuterID).css("position","static");
        };

        /* =========== INTERNAL FUNCTIONS END ============== */

        // Create iFrame
        $('<iframe />', {
            name: 'jqIFramePopup',
            id:   'jqIFramePopup',
            src:   url,
            frameborder: 0,
            allowtransparency: 'true',
            style: 'border: none; background: transparent;  position: absolute; display:none; width:' + options.width + 'px; height:' + options.height + 'px;z-index: 999999;'
        }).appendTo('body');

        // reset the iframe height on load to the document height?
        if (options.autoHeight){
            $('iframe#jqIFramePopup').load(function(){
                this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
                parent.$('#jqIFramePopup').jqCentre();
            });
        }

        // create close button and add to popup
        $('iframe#jqIFramePopup').load(function()
        {
            var oBody = $("#jqIFramePopup").contents().find("body");
            oBody.append('<a id="jqIFrameCloseBtn" onclick="parent.$.fn.jqIframe.closePopup();" href="#"></a>');
        });


        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        $('#jqIFramePopup').jqCentre();


        // Show  teh mask
        $.fn.jqIframe.showMask();


        // if mask is clicked close it
        $('#jqIFrameMask').click(function () {  $.fn.jqIframe.closePopup();    });
        // or if user presses Esc
        $(document).keypress(function(e){ if(e.keyCode==27 ){ $.fn.jqIframe.closePopup(); }});

       /*  SHow the popup   */
        $('#jqIFramePopup').fadeIn("500");

        /* bind a resize handler to adjust mask and iframe size when window is resized */
        $(window).resize(function(){
            var elem = $(this);
            //Get the document height and width
            var winHeight = $(document).height();
            var winWidth = $(window).width();
            // re-set height and width to mask to fill screen
            $('#jqIFrameMask').css({'width':winWidth,'height':winHeight});


            // Centre iframe
            $('#jqIFramePopup').jqCentre();

        });

        return(false); // prevent click actions
    };
})(jQuery);

jQuery.fn.jqCentre = function () {
    this.css("position","absolute");
    var top = (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop();
    if (top < 10 ) top = 10;
    this.css("top", top + "px");
    var left = (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() ;
    if (left < 0 ) left = 0;
    this.css("left", left+ "px");
    return this;
}

/*  =======================================

/*
* Add a function to jQuery to automate popup windows.
*/
function jqNewWin(url, winWidth, winHeight){
    return ( $.fn.popWindow(url, {width:winWidth, height: winHeight }) );
}

(function($){
    $.fn.popWindow = function(url, options) {
    // Declare some default values.
    var defaults = {
        width: 0,
        height:0,
        left: 0,
        top: 0,
        location: 0,
        directories: 0,
        status: 0,
        toolbar: 0,
        menubar: 0,
        resizable: 1,
        scrollbars: 1,
        url: '',
        name: 'cms_win',
        center: 1
    };

    // Merge the defaults with the options parameter.
    var options = $.extend(defaults, options);

    if (options.width == 0 ) options.width = screen.width *.9;
    if (options.height == 0 ) options.height =screen.height *.8;

    // Set the left and top if we're centering.
    if (options.center){
        options.left = (screen.width - options.width)/2;
        options.top = (screen.height - options.height)/2;
    }

    // Concatenate the window.open() function's options.
    var features = "width="+options.width+",height="+
        options.height+",left="+options.left+",top="+
        options.top+",location="+options.location+
        ",directories="+options.directories+",status="+
        options.status+",toolbar="+options.toolbar+
        ",menubar="+options.menubar+",scrollbars="+
        options.scrollbars+",resizable="+
        options.resizable;

    // open a new window with these arguments.
    window.open(url,options.name,features);
    return false;
};
})(jQuery);

